I want to pait a red border on textfields in which the user enters an invalid value. This fields can have a invalid value even if the user hasn´t edited them, for example a null value on a DateFormatter. Or a null value on a NumberFormatter. That is why I'm using a FocusListener.
Here are two classes that do what I need, however, when the application sets or changes the value without user input, then the field keeps appearing as invalid.
I am not sure if I should use "look and feel" as a solution, or maybe "actions". Do you see a good OOP approach on the way I am trying to implement this need?
Thanks in advance.
public class Form {
private java.util.ArrayList<JComponent> list = new java.util.ArrayList();
private TextVerifier verifier;
public Form() {
verifier = new TextVerifier();
}
public void add(JComponent c) {
if (c instanceof JFormattedTextField) {
((JFormattedTextField)c).setFocusLostBehavior(JFormattedTextField.COMMIT);
c.addFocusListener(verifier);
}
}
public void clear() {
for (JComponent c : list) {
verifier.unmark(c);
}
}
}
public class TextVerifier implements FocusListener {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
if (e.getSource() instanceof JFormattedTextField) {
JFormattedTextField field = (JFormattedTextField)e.getSource();
if (isValid(field)) {
unmark(field);
}
else {
mark(field);
}
}
}
public void mark(JComponent component) {
if (component!=null) {
component.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.red, 1));
}
}
public void unmark(JComponent component) {
if (component!=null) {
component.setBorder(null);
}
}
public boolean isValid(JFormattedTextField field) {
JFormattedTextField.AbstractFormatter formatter = field.getFormatter();
if (formatter != null) {
try {
formatter.stringToValue(field.getText());
}
catch (java.text.ParseException e) {
return false;
}
}
return true;
}
}