Unresponsive KeyListener for JFrame

By | July 13, 2019

Question

I’m trying to implement a KeyListener for my JFrame. On the constructor, I’m using this code:

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"); }
});

When I run it, the test message comes up in my console. However, when I press a key, I don’t get any of the other messages, as if the KeyListener was not even there.

I was thinking that it could be because the focus is not on the JFrame
and so they KeyListener doesn’t receive any events. But, I’m pretty sure it is.

Is there something that I am missing?

Solution

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);

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *