Java Reference
In-Depth Information
Listening to JTextField Events with an InputVerifier
Implementing the InputVerifier interface allows you to do field-level validation of a JTextField .
Before focus moves out of a text component, the verifier runs. If the input isn't valid, the verifier
rejects the change and keeps input focus within the given component.
In the following example, if you try to move the input focus beyond the text field, you'll
find that you can't, unless the contents of the text field are empty or the contents consist of the
string "Exit" .
InputVerifier verifier = new InputVerifier() {
public boolean verify(JComponent input) {
final JTextComponent source = (JTextComponent)input;
String text = source.getText();
if ((text.length() != 0) && !(text.equals("Exit"))) {
Runnable runnable = new Runnable() {
public void run() {
JOptionPane.showMessageDialog (source, "Can't leave.",
"Error Dialog", JOptionPane.ERROR_MESSAGE);
}
};
EventQueue.invokeLater(runnable);
return false;
} else {
return true;
}
}
};
nameTextField.setInputVerifier(verifier);
cityTextField.setInputVerifier(verifier);
Listening to JTextField Events with a DocumentListener
To find out when the contents of the text component changed, you need to associate a listener
with the data model. In this case, the data model is Document and the listener is a DocumentListener .
The following example just tells you when and how the model changed. Remember that
changedUpdate() is for attribute changes. Do not use a DocumentListener for input validation.
DocumentListener documentListener = new DocumentListener() {
public void changedUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
public void insertUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
public void removeUpdate(DocumentEvent documentEvent) {
printIt(documentEvent);
}
private void printIt(DocumentEvent documentEvent) {
DocumentEvent.EventType type = documentEvent.getType();
Search WWH ::




Custom Search