Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Mar 22, 2000

Shifting Focus Away from a JTextArea with the Tab Key

Under most circumstances, pressing the tab key within a JFC/Swing GUI application will cause the focus to shift from the currently focused Component to the next focus-traversable Component. This is not the case, however, if the currently focused Component happens to be a JTextArea object.

A JTextArea is a Component that allows multiple lines of plain text to be displayed and edited. Unlike the JTextField class, it allows a user to insert tab characters into the text with the tab key. In many cases however, the desired behavior is for the user to be able to tab away from a JTextArea without inserting a tab character. Unfortunately, the creators of JTextArea did not include a way to make a JTextArea object behave this way.

One seemingly obvious solution is to write a KeyListener that monitors KeyEvents within a JTextArea, and shifts the focus to the next Component whenever the tab key is pressed while the JTextArea is focused. The problem with this approach, however, is that the tab character will still get inserted into the JTextArea before the focus is shifted away.

The best solution I've found is to use a subclass of JTextArea whose isManagingFocus() method always returns false, instead of true. For example:

 
import javax.swing.*;

public class NoTabTextArea extends JTextArea {
    public boolean isManagingFocus() {
        return false;
    }
}
An instance of NoTabTextArea can be used exactly like a JTextArea, except that the tab key will cause the focus to shift away from it without a tab character being inserted.

Unfortunately, you will not be able to visually manipulate instances of this class within a drag-and-drop-style form designer, like Visual Cafe, Visual Age, JBuilder, etc., unless you create a JavaBean based on the class. You can still hand-code an instance into your form class, but it will probably not be visible in the form designer.

David Glasser
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap