Value Change Listener to JTextField

前端 未结 12 2102
情歌与酒
情歌与酒 2020-11-22 04:16

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

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 04:44

    it was the update version of Codemwnci. his code is quite fine and works great except the error message. To avoid error you must change the condition statement.

      // 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 (textField.getText().length()>0){
           JOptionPane.showMessageDialog(null,
              "Error: Please enter number bigger than 0", "Error Massage",
              JOptionPane.ERROR_MESSAGE);
         }
      }
    });
    

提交回复
热议问题