/*
Code revised from Desktop Java Live:
http://www.sourcebeat.com/downloads/
*/
import javax.swing.BorderFactory;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;
public class InputVerifierExample extends JPanel {
private JLabel validationLabel;
public InputVerifierExample() {
DefaultFormBuilder formBuilder = new DefaultFormBuilder(new FormLayout("right:pref, 3dlu, p:g"));
formBuilder.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JTextField javaField = new JTextField();
JTextField swingField = new JTextField();
this.validationLabel = new JLabel();
javaField.setInputVerifier(new StrictInputVerifier("Java"));
swingField.setInputVerifier(new StrictInputVerifier("Swing"));
formBuilder.append("Java Field:", javaField);
formBuilder.append("Swing Field:", swingField);
formBuilder.appendParagraphGapRow();
formBuilder.append(validationLabel, 3);
add(formBuilder.getPanel());
}
private class StrictInputVerifier extends InputVerifier {
private String validString;
public StrictInputVerifier(String validString) {
this.validString = validString;
}
public boolean verify(JComponent input) {
JTextField textField = (JTextField) input;
if (validString.equals(textField.getText())) {
validationLabel.setText("");
return true;
} else {
validationLabel.setText("Field must only contain " + this.validString);
return false;
}
}
}
public static void main(String[] a){
JFrame f = new JFrame("Input Verifier Example");
f.setDefaultCloseOperation(2);
f.add(new InputVerifierExample());
f.pack();
f.setVisible(true);
}
}
jgoodiesValidation.zip( 277 k)