Highlight Text Automatically

When the focus of a graphical user interface shifts to an empty TextField, you type the desired input and step to the next one. But if the TextField is not empty, the input cursor appears at the position it had when the Component previously lost the focus, and the characters you type augment those present. This behavior may be acceptable, but if the content of the field is more likely to be replaced than modified, then you can streamline the interface by highlighting the existing text when the field receives the focus. Then the user’s input will replace all the characters as soon as typing starts. If the user does want to modify the existing content, a second click to position the input cursor will also turn off the highlight. You can extend the TextField class to adjust the highlight during the focus events:

 import java.awt.*;import java.awt.event.*;public class InpatientField extends TextField                         implements FocusListener {// Constructor    public InpatientField(String entry, int width) {        super(entry, width);        addFocusListener(this);    }// Focus event handlers    public void focusGained(FocusEvent ev) {        selectAll();    }    public void focusLost  (FocusEvent ev) {        select(0, 0);    }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: