2
Usually when I need to validate a text field without using action events, I use focus events such as those available from the interface FocusListener
.
In this example, I check if the field was filled when losing focus, and return the focus to it, with a red border, if it has not been 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 found that the swing API has the class Inputverifier, that allows me to do the same thing without having to spend focus listeners, which can be useful for other resources.
How this class works InputVerifier
and how I use it to ensure that a field is filled before losing focus, as in the example?