views:

27

answers:

1

I want the message box appear immediately after the user change the value in textfield. Currently I need to hit enter key to get the message box pop out. Anything wrong to 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 Massage",
                                    JOptionPane.ERROR_MESSAGE);
                        }       
     }
}
A: 

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

// Listen for changes in the text
myTextField.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 Massage",
          JOptionPane.ERROR_MESSAGE);
     }
  }
});
Codemwnci
Hi it doesnt work, even hit enter key.
there is an error
I have updated the solution. This should monitor changes to the text field.
Codemwnci
Thanks you very much