How to add a listener to a JTextField for up, down left, right arrow?
I need to write an arrow listener for my JTextField. if a try with:
publi开发者_如何学Pythonc void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
......
}
}
...
This is not good.( I think that JTextField is not responding to a special key listener.)
I know the accepted answer given above will work, but this is not the way it SHOULD be done in Swing. KeyListeners should generally only be used in AWT applications because they don't support a more abstract API.
When using Swing you SHOULD be using Key Bindings. All Swing components use Key Bindings. The Key Bindings blog entry gives some basics on how to use them and contains a link to the Swing tutorial on "How to Use Key Bindings" for more detailed information.
You have to use keyPressed or keyReleased here. Quoting from SUN's API javadoc:
"Key typed" events are higher-level and generally do not depend on the platform or keyboard layout. They are generated when a Unicode character is entered
Therefore, the keyTyped method will not be called for the arrow keys, as they do not generate Unicode characters.
You can add your own KeyListener
via addKeyListener
method provided for every java.awt.Component
. In your Listener, use keyPressed
.
Arrow keys are action keys, you can verify this event via isActionKey
:
Returns true if the key firing the event is an action key. Examples of action keys include Cut, Copy, Paste, Page Up, Caps Lock, the arrow and function keys. This information is valid only for key-pressed and key-released events.
See also: http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
精彩评论