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?
KeyListeners need to be on the focused component to work. One solution is to give your component the focus after first making it focusable. Better by a long shot however is to use Key Bindings. Google the tutorial on this.
A Simple KeyListener Java ClassCreate a new KeyListener object. Override the methods that correspond to the key events you want to monitor e.g keyPressed , keyReleased , keyTyped . Create a JTextField component. Use it's addKeyListener method to add to it the KeyListener you've created.
Methods of Java KeyListener The following are the commonly used methods: KeyPresses(KeyEventev): This method will be invoked when Key is pressed. KeyReleased(KeyEventev): This method will be invoked when a key is released. KeyTyped(KeyEventev): This method will be invoked when Key is typed.
If you don't want to register a listener on every component,
you could add your 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); } }
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With