Wednesday, April 28, 2010

Perform an Event when “Enter” key is pressed

For this month since I had very limited time to come up with a post, I thought of discussing about this common yet simple question that many newbie have in mind.

Let’s say I have a JTextField and a JTextArea and every time when I press the “ENTER” key on the JTextfield, I need to append the text from the JTextField to the JTextArea.

This is a very simple scenario and to accomplish this we have to make use of the “KeyAdapter Class (which implements the KeyListener Interface)” and “KeyEvent Class”.

Once the key “Enter” is pressed we need to perform the action, so at this point we need to make use of the “keyReleased(KeyEvent evt)” method from the adapter class and then check if the keycode is equals to “evt.VK_ENTER”. The code snippets are as below.

For further reference and study kindly refer to this link http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html

Author: Thiagu