Avoiding Tab Traversal for Non-Editable TextFields

To prevent a component from getting the focus when the Tab or shift-Tab keyboard focus traversal is used, override the isFocusTraversable method. It is often desirable to toggle a TextField in an interface so that it allows input at some times and disallows it at others. One way to do this is to disable the TextField using setEnabled(), but this approach has the disadvantage of changing the appearance of the TextField. Alternatively, you can use setEditable() to make the TextField read-only without changing its appearance. Unfortunately, disabling editing of the TextField does not prevent the Tab and shift-Tab key sequences from transferring the focus to the field. The result is that Tab and shift-Tab will transfer the focus to a TextField that cannot be edited. This behavior is annoying for users who are accustomed to tabbing through interface components, but expect the “inactive” components to be skipped. To provide a user-friendly interface, you can create a subclass of TextField, which will behave somewhat more intuitively:

 public class SmartTabTextField extends TextField {	/**	 *  If this component is not editable, it should also not receivethe focus	 *  as a result of Tab or shift-Tab being pressed.	 */	public boolean isFocusTraversable() {		return isEditable();	}}

This code does not prevent the TextField from getting the focus when it is explicitly selected, such as with a left mouse button click. However, it will prevent unexpected occurrences when the user is simply tabbing through a series of interface components.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: