Key Listeners

How to add java.awt.KeyListener to a javax.swing.JTree

heres wat i am using the problem is that you can only hit one of the buttons at once i need to be able to hit shift and up at same time or conrotl and down and so on
public void keyPressed(KeyEvent e)
     switch (e.getKeyCode())
          case KeyEvent.VK_DOWN:
          if (p2y <= 450)
               p2y += 15;
          break;
          case KeyEvent.VK_UP:
          if (p2y >= -10)
               p2y -= 15;
          break;
          repaint();
     switch (e.getKeyCode())
          case KeyEvent.VK_SHIFT:
          if (p1y >= -10)
               p1y -= 15;
          break;
          case KeyEvent.VK_CONTROL:
          if (p1y <= 450)
               p1y += 15;
          break;
          repaint();
                 }

Similar Messages

  • Key listeners without a component?

    Hey guys,
    So I have an application with several sliders, buttons, etc. and I would like to set shortcuts for certain parts of it. For example, when the user presses the "n" key, one of the sliders should increase in value. I have looked into this, and found that key listeners only work on a component that has the keyboard focus. Does this mean I should give my main JPanel the keyboard focus and make the shortcuts change the sliders in that listener? What happens if the focus changes from the main panel to one of the buttons and the key is then pressed, will it still call the key listener on the JPanel?
    The best way would be if there was a listener that just listens to the keyboard and is called when a key is pressed, without any need for a specific component. Does anyone know of a way to do this? Thanks beforehand!
    Cheers,
    Lukas

    Young_one wrote:
    Well, the problem is I have 3 applets running on the same page, and so, they don't all have focus at the same time, but the key bindings need to work at any time, no matter which applet the user last clicked in. So I guess the question is if there is a way to create a listener that is not attached to a specific components focus. I would think that a listener that just listens to the keyboard doesn't have to specify a focus, but I guess it does? Thanks for all your help so far.Ah, I'm not an applet expert, but as far as I know, key binding and key listeners require that the app doing the listening have focus: with key listeners the component itself has to have focus, but with key binding, the component that is assigned the binding doesn't have to have focus, but at the very least the window that holds it does. I know of no way around this through standard Java.

  • Multi Key Listeners??

    In a nutshell, I've got a zoom tool (magnifying glass cursor)
    that toggles between the plus/minus when the user presses CONTROL.
    I have also created a class file with my magnifying functions in it
    - it shrinks the target when the user is holding down the CONTROL
    key. Both listeners work when activated individually, but not at
    the same time.
    Does anyone know how I can make these two listeners work
    together, short of packaging the cursor with the class?
    thanks to anyone with input.
    Jim

    I tried using various keys and key combinations, the latest
    being control + N. Here is the list of Flash Shortcuts that I could
    find:
    Press this To do this
    CTRL+O Open a file
    SHIFT+CTRL+O Open from web
    SPACEBAR Play or pause an open animation
    PERIOD Stop the playback
    CTRL+LEFT ARROW, NUMPAD 4 Previous movie
    CTRL+RIGHT ARROW, NUMPAD 6 Next movie
    LEFT ARROW Rewind 20 frames
    RIGHT ARROW Forward 20 frames
    ALT+LEFT ARROW Rewind 1 frame
    ALT+RIGHT ARROW Forward 1 frame
    ALT+ENTER, F11 Enter/exit fullscreen mode
    ESC (Fullscreen mode) Return from Fullscreen mode
    ALT (Fullscreen mode) Show/hide the seek bar and controls
    ALT+E Show/hide the Playlist Editor window
    ALT+G Toggle Game Mode
    ALT+S Take a snapshot
    CTRL+UP ARROW Volume Up
    CTRL+DOWN ARROW Volume Down
    CTRL+M Mute

  • Key listeners triggering Flash IDE tools instead of SWF events

    During Test Movie in the Flash CS3 authoring environment,
    some keys are being trapped by Flash iteself and are not getting
    passed to my SWF. These are any that are assigned to Tools, like
    S(Ink Bottle), K (Paint Bucket), P (Pen), etc. The Test Movie SWF
    is the active window and I've clicked within it. Why are my keys
    getting trapped by Flash and not the SWF? Keys that are not
    assigned to Tools are working fine in my SWF.
    Any help greatly appreciated. Code snippets attached.
    SB

    Never mind... Test Movie's menu -> Disable Keyboard
    Shortcuts did the trick.

  • How to add key listeners to jcombobox

    i have been trying to add an key listener to jcombobox so that i can identify when an enter key is pressed.

    You should use an ActionListener to handle the enter key. See the section from the Swing toturial on "Using Combo Boxes":
    http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html#listeners

  • Can someone help with key listeners... :(

    on (keyPress "q") {
    nextFrame();
    on (keyPress "w") {
    nextFrame();
    on (keyPress "e") {
    nextFrame();
    I'm creating an app for television that emulates a google search engine. The keypress codes i used were to "fake" a person entering a search field. My problem is the KeyPress command no longer works when fullscreen. I've read that keylisteners work fullscreen but am entirely unfamiliar with that code.
    If someone could provide me a script example that would effectively replicate the same function I would greatly appreciate it.

    Mo_73 wrote:
     I'm creating an app ...
    Using what - Flash, Flex, ActionScript, ...?  Please post in the appropriate forum; this is the Flash Player forum.

  • How to block JTree key event listeners

    I have a JToolbar I am managing keyboards events for (e.g. PageUp, PageDown, right, left, up, down). I also have a JTree in another panel. I have to use 'Alt + PageUp' instead of PageUp because, if I use 'PageUp' (without also using the Alt key), and, the JTree gets the focus, then the JTree will respond to 'PageUp' instead of my JToolbar.
    I have my key actions in a 'getKeystrokeActions()' method which I pass the JToolbar into so I tried passing the JTree to the same method. This doesn't quite do what I want as both components now respond to a 'PageUp' key event.
    There must be some way to tell the JTree not to handle key events but I can't seem to find it. Any help much appreciated.

    Remove the key listeners?
    JTree tree = new JTree();
    for(KeyListener listener : tree.getKeyListeners()) {
        tree.removeKeyListener(listener);
    }Another option would be to just do
    tree.setFocasable(false);

  • Key Press to Play Video, in multi-screen project

    I have a timeline with multiple videos in it, all loaded as external videos with playback controls as the audio is important (all are 55 seconds long and high quality audio is vital). First of all I want a specific key pressed to play one of the videos. I've been playing around with event handlers, key press event, but nothing has worked.
    This is a multi screen project I'm working on so is there any way to have two seperate windows of video 1080x1920 (that would play on two seperate screens to interact with eachother) or would I have to create a stage twice the width. I need two video clips to play simultaniously once a key is pressed.
    I am a real beginner to flash so I really have no idea whether this is possible.
    I'm doing this on Flash CS6 on a Mac in IOS 10.9.2
    Thanks!

    i'm not sure what you're trying to do with multiple screens but that should have no impact on using key listeners to control your timeline:
    stage.addEventListener(KeyboardEvent.KEY_DOWN,f):
    function f(e:KeyboardEvent):void{
    trace(e.keyCode);

  • Launchd: Using Sockets key for on demand jobs

    Hi,
    I would like to start nginx whenever I send an HTTP request to localhost. This is my plist:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"
    "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    <key>Disabled</key>
    <false/>
    <key>Label</key>
    <string>org.sysoev.nginx</string>
    <key>ProgramArguments</key>
    <array>
    <string>/usr/local/nginx/sbin/nginx</string>
    </array>
    <key>Sockets</key>
    <dict>
    <key>Listeners</key>
    <dict>
    <key>SockNodeName</key>
    <string>127.0.0.1</string>
    <key>SockServiceName</key>
    <string>http</string>
    </dict>
    </dict>
    <key>KeepAlive</key>
    <dict>
    <key>SuccessfulExit</key>
    <false/>
    </dict>
    </dict>
    </plist>
    Although nginx is started when I request a webpage from localhost, the request never arrives at nginx, so the requested page is not loaded. When I replace the Sockets dict with RunAtLoad: true, all works fine.
    Could it be that launchd somehow intercepts the requests sent to an on-demand daemon?
    Kind regards,
    Jan

    Launchd does intercept the requests sent to an on-demand process. That's how launch on demand works.
    I'm not familiar with nginx, but I wouldn't expect launch on demand to work with any web server, for the same reason it doesn't work with Apache. Apache has to start up as root in order to bind the usual ports 80 and 443. It then forks an unprivileged process to handle the actual network traffic. Any sort of automatic forking is incompatible with launch on demand. The solution is the one you already found, run at launch and let the process do its own listening on the network.

  • Default button being clicked multiple times when enter key is pressed

    Hello,
    There seems to be a strange difference in how the default button behaves in JRE 1.4.X versus 1.3.X.
    In 1.3.X, when the enter key was pressed, the default button would be "pressed down" when the key was pressed, but wouldn't be fully clicked until the enter key was released. This means that only one event would be fired, even if the enter key was held down for a long time.
    In 1.4.X however, if the enter key is pressed and held for more than a second, then the default button is clicked multiple times until the enter key is released.
    Consider the following code (which is just a dialog with a button on it):
    public class SimpleDialog extends JDialog implements java.awt.event.ActionListener
    private JButton jButton1 = new JButton("button");
    public SimpleDialog()
    this.getContentPane().add(jButton1);
    this.getRootPane().setDefaultButton(jButton1);
    jButton1.addActionListener(this);
    this.pack();
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == jButton1)
    System.out.println("button pressed");
    public static void main(String[] args)
    new SimpleDialog().show();
    When you compile and run this code under 1.3.1, and hold the enter key down for 10 seconds, you will only see one print line statement.
    However, if you compile and run this code under 1.4.1, and then hold the enter key down for 10 seconds, you will see about 100 print line statements.
    Is this a bug in 1.4.X or was this desired functionality (e.g. was it fixing some other bug)?
    Does anyone know how I can make it behave the "old way" (when the default button was only clicked once)?
    Thanks in advance if you have any advice.
    Dave

    Hello all,
    I think I have found a solution. The behaviour of the how the default button is triggered is contained withing the RootPaneUI. So, if I override the default RootPaneUI used by the UIDefaults with my own RootPaneUI, I can define that behaviour for myself.
    Here is my simple dialog with a button and a textfield (when the focus is NOT on the button, and the enter key is pressed, I don't want the actionPerformed method to be called until the enter key is released):
    package focustests;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class SimpleDialog extends JDialog implements java.awt.event.ActionListener
    private JButton jButton1 = new JButton("button");
    public SimpleDialog()
    this.getContentPane().add(new JTextField("a text field"), BorderLayout.NORTH);
    this.getContentPane().add(jButton1, BorderLayout.SOUTH);
    this.getRootPane().setDefaultButton(jButton1);
    jButton1.addActionListener(this);
    this.pack();
    public void actionPerformed(ActionEvent e)
    if (e.getSource() == jButton1)
    System.out.println("button pressed");
    public static void main(String[] args)
    javax.swing.UIManager.getDefaults().put("RootPaneUI", "focustests.MyRootPaneUI");
    new SimpleDialog().show();
    and the MyRootPaneUI class controls the behaviour for how the default button is handled:
    package focustests;
    import javax.swing.*;
    * Since we are using the Windows look and feel in our product, we should extend from the
    * Windows laf RootPaneUI
    public class MyRootPaneUI extends com.sun.java.swing.plaf.windows.WindowsRootPaneUI
    private final static MyRootPaneUI myRootPaneUI = new MyRootPaneUI();
    public static javax.swing.plaf.ComponentUI createUI(JComponent c) {
    return myRootPaneUI;
    protected void installKeyboardActions(JRootPane root) {
    super.installKeyboardActions(root);
    InputMap km = SwingUtilities.getUIInputMap(root,
    JComponent.WHEN_IN_FOCUSED_WINDOW);
    if (km == null) {
    km = new javax.swing.plaf.InputMapUIResource();
    SwingUtilities.replaceUIInputMap(root,
    JComponent.WHEN_IN_FOCUSED_WINDOW, km);
    //when the Enter key is pressed (with no modifiers), trigger a "pressed" event
    km.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER,
    0, false), "pressed");
    //when the Enter key is released (with no modifiers), trigger a "release" event
    km.put(KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ENTER,
    0, true), "released");
    ActionMap am = SwingUtilities.getUIActionMap(root);
    if (am == null) {
    am = new javax.swing.plaf.ActionMapUIResource();
    SwingUtilities.replaceUIActionMap(root, am);
    am.put("press", new HoldDefaultButtonAction(root, true));
    am.put("release", new HoldDefaultButtonAction(root, false));
    * This is a copy of the static nested class DefaultAction which was
    * contained in the JRootPane class in Java 1.3.1. Since we are
    * using Java 1.4.1, and we don't like the way the new JRE handles
    * the default button, we will replace it with the old (1.3.1) way of
    * doing things.
    static class HoldDefaultButtonAction extends AbstractAction {
    JRootPane root;
    boolean press;
    HoldDefaultButtonAction(JRootPane root, boolean press) {
    this.root = root;
    this.press = press;
    public void actionPerformed(java.awt.event.ActionEvent e) {
    JButton owner = root.getDefaultButton();
    if (owner != null && SwingUtilities.getRootPane(owner) == root) {
    ButtonModel model = owner.getModel();
    if (press) {
    model.setArmed(true);
    model.setPressed(true);
    } else {
    model.setPressed(false);
    public boolean isEnabled() {
    JButton owner = root.getDefaultButton();
    return (owner != null && owner.getModel().isEnabled());
    This seems to work. Does anyone have any comments on this solution?
    Tjacobs, I still don't see how adding a key listeners or overriding the processKeyEvent method on my button would help. The button won't receive the key event unless the focus is on the button. There is no method "enableEvents(...)" in the AWTEventMulticaster. Perhaps you have some code examples? Thanks anyway for your help.
    Dave

  • Removing all tab key events

    Hallo all,
    I am having another problem with my JTables. Because our customer doesn't want to get out of JTable via Ctrl+TAB we have customized the TAB Key behaviour and it skips to the following component and it is fine. But if I go to a cell via TAB key (for example cell(3,4)) and if I select another component above via mouse button and go through the table via TAB key it focuses on the cell (4,4) instead of cell(0,0). How can I solve this problem? How can I refresh or remove the key listeners of the Table after I left the table via mouse? Can anyone help me?

    (Untested, and there may be a better approach)
    I would try adding a FocusListener and in the focusLost, something liketable.getSelectionModel().clearSelection();
    table.getColumnModel().getSelectionModel().clearSelection();luck, db
    edit No that didin't do it. Try this one:table.setRowSelectionInterval(0, 0);
    table.setColumnSelectionInterval(0, 0);Edited by: Darryl.Burke

  • Problem in Tab Keys

    Hi
    I am trying to write a KeyListener that can detect when the tab key is pressed within a JTextField. The Listener detects all keys accept the tab key. It seems that some lower level method is consuming the key before it get to my listener.
    My application needs to put up a dialog if the tabs out of the text field.
    Any help would be appreciated.

    Hi,
    Yes, there is a lower-level method that dispatches all events generated from a component and sends the events to the appropriate listener for that component.
    You need to subclass JTextField and override processKeyEvent(KeyEvent key). Any type of key event generated from this component, this method will dispatch the event to all of this components key listeners, so there will be some processing that blocks the TAB key.We can override the method and perform our own processing, and then call super.processKeyEvent(KeyEvent) to handle all other key events other than TAB.
    Try the below code this showa how to catch the TAB key .
    class CustomTextField extends JTextField {
    public CustomTextField( int c){
    super(c);
    protected void processKeyEvent(KeyEvent ke){
    if( ke.getKeyCode() == KeyEvent.VK_TAB)
    System.out.println("TAB");
    //you must call this!!
    super.processKeyEvent( ke);
    Hope this will help you.
    Anil
    Developer Technical Support,
    Sun Microsystems Inc,
    http://www.sun.com/developers/support

  • 'Enter' key listener!

    When I press a button (mouse clik on the button) my application makes something (!). How can I do that the application to make the same thing when I pres 'Enter' key? I used accelerators and key listeners but it does work how I want. More informations: I have a JComboBox and when I write something in it and I press a button (or 'Enter' - I want...) the application adds items in this JComboBox...

    hello,
    u dont need to to use any keylistener, just add an actionlistener to the component and the enter key will be enabled. so if u want to enable it on the combobox than u will do something like:
    comboBox.addActionListener(new ActionListener()
    public void actionPerfored(ActionEvent e)
    //your actions here
    );to enable the enter key on a form, u could make use of this code:
    UIManager.getDefaults().put("Button.focusInputMap", new
              UIDefaults.LazyInputMap(new Object[] {
              "ENTER", "pressed",
              "released ENTER", "released"
              }));asrar

  • SetFocus messes up key listener

    I have a textfield attached to a movieclip attached to a
    movieclip on the stage. I have an object set to listen for key
    events, and that object defines an onKeyDown function. If I run the
    movie and click on the textfield manually, a cursor appears in the
    textfield, and when I enter text the onKeyDown function executes.
    If instead I use Selection.setFocus(myTextfield), the cursor
    does not appear, but I can still type text in the textfield.
    However, this apparently makes a big difference, because now the
    onKeyDown function in the key-listener object does not execute. Is
    there a way to programmatically set focus and still have key
    listeners work? What is the difference between the
    Selection.setFocus kind of focus and the other kind of focus when a
    cursor appears?

    create an array. it's quick and easy if you work cleverly.
    create an empty array and push your ascii keypress codes into
    it. then test your project and keypress the numbers and letters in
    the order you want them to be listed in your array.
    when you're finished trace your array (in order), copy the
    output panel and in the authoring environment paste your ascii
    array.

  • Return key as button accelerator

    I ahve been developing a swing based application for a while and it is nearing competion. I have however got just one problem left. Most of my users are on windows and as you probably know windows uses the return key for button presses where as java uses the spacebar.
    What I would like to know is there any way to change this or have both active with out goign through and putting key listeners on everything etc etc. Setting mnenomics and the like seems simple so I am sure this is simple as well but I cant seem to find it.
    TIA

    You set the default button as follows:
    getRootPane().setDefaultButton( button1 );
    However, if you have more than one button, then tabbing through each button and going back to a text field will cause the last button to become the default button. I reset the default button with the following FocusListener:
    FocusAdapter resetDefaultButton = new FocusAdapter()
         public void focusLost(FocusEvent e)
              getRootPane().setDefaultButton( button1 );
    button2.addFocusListener( resetDefaultButton );
    button3.addFocusListener( resetDefaultButton );
    button4.addFocusListener( resetDefaultButton );
    Try it without the FocusListener first. Hope this helps.

Maybe you are looking for