javaswinglistenerjtextfielddocumentlistener

Value Change Listener to JTextField


I want the message box to appear immediately after the user changes the value in the textfield. Currently, I need to hit the enter key to get the message box to pop out. Is there anything wrong with my code?

textField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {

        if (Integer.parseInt(textField.getText())<=0){
            JOptionPane.showMessageDialog(null,
                    "Error: Please enter number bigger than 0", "Error Message",
                    JOptionPane.ERROR_MESSAGE);
        }       
    }
}

Any help would be appreciated!


Solution

  • Add a listener to the underlying Document, which is automatically created for you.

    // Listen for changes in the text
    textField.getDocument().addDocumentListener(new DocumentListener() {
      public void changedUpdate(DocumentEvent e) {
        warn();
      }
      public void removeUpdate(DocumentEvent e) {
        warn();
      }
      public void insertUpdate(DocumentEvent e) {
        warn();
      }
    
      public void warn() {
         if (Integer.parseInt(textField.getText())<=0){
           JOptionPane.showMessageDialog(null,
              "Error: Please enter number bigger than 0", "Error Message",
              JOptionPane.ERROR_MESSAGE);
         }
      }
    });