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:
- Consume the KeyEvent with the method Component.consume() in the keyPressed() handler.
- 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.