Display dialog in InputVerifier from JTextField in Java
Description
The following code shows how to display dialog in InputVerifier from JTextField.
Example
import java.awt.FlowLayout;
/* w w w . j a v a2 s . c om*/
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;
public class Main {
public static void main(String[] args) {
JFrame f = new JFrame("Text Field Elements");
f.setLayout(new FlowLayout());
JTextField textfield = new JTextField(10);
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);
}
};
SwingUtilities.invokeLater(runnable);
return false;
} else {
return true;
}
}
};
textfield.setInputVerifier(verifier);
f.add(textfield);
f.pack();
f.setVisible(true);
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »