Normally when I need to validate a text field without using action events, I use focus events, such as those available through the FocusListener
.
In this example, I check if the field was filled out when I lost focus, and I returned the focus to it with a red border if it was not already filled:
textField.addFocusListener(new FocusAdapter(){
Border originalBorder;
@Override
public void focusLost(FocusEvent e){
JTextComponent comp = (JTextComponent) e.getSource();
if(comp.getText().trim().isEmpty()){
originalBorder = originalBorder == null ? comp.getBorder() : originalBorder;
comp.setBorder(BorderFactory.createLineBorder(Color.red, 2));
comp.requestFocus();
} else {
if(originalBorder != null) {
input.setBorder(originalBorder);
originalBorder = null;
}
}
});
However, I discovered that the swing API has the class InputVerifier , which allows me to do the same thing without having to spend focus listeners, which may be useful for other features.
How does this class InputVerifier
work and how do I use it to ensure that a field is populated before losing focus, as in the example?