views:

7601

answers:

6

Hey all,

I am trying to implement a KeyListener into my JFrame. I have used the following code (at the moment im just trying to get this to work with my JFrame).

        System.out.println("test");
        addKeyListener(new KeyListener()
        {
            public void keyPressed(KeyEvent e) { System.out.println( "tester"); }

            public void keyReleased(KeyEvent e) { System.out.println("2test2"); }

            public void keyTyped(KeyEvent e) { System.out.println("3test3"); }
        });

This is currently located in my default constructor. The "test" comes up in my console, however, when I press a button, I am not getting any other messages, as if the key listener was not even there. I was thinking possibly that it is because the focus is not on the JFrame and so they KeyListener is not working, but i'm pretty sure it is

Is there something that I am missing?

Thanks again in advance,

Tomek

+1  A: 

Hmm.. what class is your constructor for? Probably some class extending JFrame? The window focus should be at the window, of course but I don't think that's the problem.

I expanded your code, tried to run it and it worked - the key presses resulted as print output. (run with Ubuntu through Eclipse):

   public class MyFrame extends JFrame {
    public MyFrame() {
         System.out.println("test");
         addKeyListener(new KeyListener() {
          public void keyPressed(KeyEvent e) {
           System.out.println("tester");
          }

          public void keyReleased(KeyEvent e) {
           System.out.println("2test2");
          }

          public void keyTyped(KeyEvent e) {
           System.out.println("3test3");
          }
         });
        }

        public static void main(String[] args) {
         MyFrame f = new MyFrame();
         f.pack();
         f.setVisible(true);
        }
    }
Touko
I get all of the messages output also. Run in Windows command line.
Darrel
You get all the messages because in this example the JFrame has the focus. try adding a TextBox component to the JFrame and see what happens.
bruno conde
+8  A: 

Hi Tomek.

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:

myComponent.setFocusable(true);
bruno conde
yea you were right, when the program starts you can slightly see that the focus is on the button A. adding a keylistener to each button fixed this. thats a little weird, i would think that adding a keylistener to the JFrame would work but i guess not. Thanks!
Tomek
+4  A: 

KeyListener is low level and applies only to a single component. Despite attempts to make it more usable JFrame creates a number of component components, the most obvious being the content pane. JComboBox UI is also often implemented in a similar manner.

It's worth noting the mouse events work in a strange way slightly different to key events.

For details on what you should do, see my answer on Application wide keyboard shortcut - Java Swing.

Tom Hawtin - tackline
+1  A: 

I got the same problem until i read that the real problem is about FOCUS the your JFrame has already added Listeners but tour frame is never on Focus because you got a lot of components inside your JFrame that also are focusable so try

JFrame.setFocusable(true);

Good Luck

+1  A: 

If you don't want to install a listener on every component you could add you own KeyEventDispatcher to the KeyboardFocusManager.

public class MyFrame extends JFrame {    
private class MyDispatcher implements KeyEventDispatcher {
    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        if (e.getID() == KeyEvent.KEY_PRESSED) {
            System.out.println("tester");
        } else if (e.getID() == KeyEvent.KEY_RELEASED) {
            System.out.println("2test2");
        } else if (e.getID() == KeyEvent.KEY_TYPED) {
            System.out.println("3test3");
        }
        return false;
    }
}
public MyFrame() {
    add(new JTextField());
    System.out.println("test");
    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    manager.addKeyEventDispatcher(new MyDispatcher());
}

public static void main(String[] args) {
    MyFrame f = new MyFrame();
    f.pack();
    f.setVisible(true);
}

}

Peter
Thanks. Simple solution works well.
Dan Howard
A: 

hello is it possible for me to close a window, JFrame if i may by pressing a specified on my keyboard....with out having to go to the x icon in the upper right hand corner...

thnks in advance

Deion