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.

Display dialog in InputVerifier from JTextField in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer