Jose Sandoval Google
 Resume     Book     Software     Drawings     Home     Subscribe to RSS feed Search Web Search josesandoval.com

Java Swing: JTextArea ignore tab and enter key
Tuesday, November 20, 2007

This is probably a very weird title if you are not looking for a particular solution to this problem.

But why would anyone want to suppress the TAB and ENTER key inside a JTextArea component?

Well, some people like to traverse through fields in a Java JFC/Swing application by clicking the TAB or ENTER key. And if you have tried to traverse to the next field using the TAB key while inside a JTextArea component, it can't be done by default.

I looked for a reasonable solution, and I couldn't find anything that worked or didn't looked like a hack (replacing the chars with empty fields didn't look so elegant in the code). Let me save you some time by putting the solution I came up with:
  1. Consume the KeyEvent with the method Component.consume() in the keyPressed() handler.

  2. Then, traverse to the next field in the app with JTextArea.getNextFocusableComponent().requestFocusInWindow().
A couple of notes, before the code: first, it tricks the application to use the ENTER key to traverse the fields (looks like you are using the TAB key); second, it uses the deprecated method getNextFocusableComponent().

The code is here, and the running application is here. Note that IE takes over the TAB key, so use ENTER so the required effect; if you are using FireFox, you are fine.


1:59 AM | 0 comment(s) |

Comments:


This page is powered by Blogger. Isn't yours?

Guestbook
© Jose Sandoval 2004-2009 jose@josesandoval.com