artaxerxe
artaxerxe

Reputation: 6411

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:

public 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.)

Upvotes: 3

Views: 3474

Answers (3)

camickr
camickr

Reputation: 324147

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.

Upvotes: 5

miku
miku

Reputation: 188114

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

Upvotes: 1

Frank
Frank

Reputation: 10571

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.

Upvotes: 2

Related Questions