我希望消息框在用户更改文本字段中的值后立即出现。目前,我需要按回车键来弹出消息框。我的代码有什么问题吗?

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);
        }       
    }
}

任何帮助都将不胜感激!


当前回答

这里是@Boann的答案的Kotlin移植,这是一个很好的解决方案,对我来说一直很有效。

import java.beans.*
import javax.swing.*
import javax.swing.event.*
import javax.swing.text.*

/**
 * Installs a listener to receive notification when the text of this
 * [JTextComponent] is changed. Internally, it installs a [DocumentListener] on the
 * text component's [Document], and a [PropertyChangeListener] on the text component
 * to detect if the `Document` itself is replaced.
 *
 * @param changeListener a listener to receive [ChangeEvent]s when the text is changed;
 * the source object for the events will be the text component
 */
fun JTextComponent.addChangeListener(changeListener: ChangeListener) {
    val dl: DocumentListener = object : DocumentListener {
        private var lastChange = 0
        private var lastNotifiedChange = 0
        override fun insertUpdate(e: DocumentEvent) = changedUpdate(e)
        override fun removeUpdate(e: DocumentEvent) = changedUpdate(e)
        override fun changedUpdate(e: DocumentEvent) {
            lastChange++
            SwingUtilities.invokeLater {
                if (lastNotifiedChange != lastChange) {
                    lastNotifiedChange = lastChange
                    changeListener.stateChanged(ChangeEvent(this))
                }
            }
        }
    }
    addPropertyChangeListener("document") { e: PropertyChangeEvent ->
        (e.oldValue as? Document)?.removeDocumentListener(dl)
        (e.newValue as? Document)?.addDocumentListener(dl)
        dl.changedUpdate(null)
    }
    document?.addDocumentListener(dl)
}

你可以在任何文本组件上使用它,如下所示:

myTextField.addChangeListener { event -> myEventHandler(event) }

就像他的代码一样,也是公有领域。

其他回答

这里是@Boann的答案的Kotlin移植,这是一个很好的解决方案,对我来说一直很有效。

import java.beans.*
import javax.swing.*
import javax.swing.event.*
import javax.swing.text.*

/**
 * Installs a listener to receive notification when the text of this
 * [JTextComponent] is changed. Internally, it installs a [DocumentListener] on the
 * text component's [Document], and a [PropertyChangeListener] on the text component
 * to detect if the `Document` itself is replaced.
 *
 * @param changeListener a listener to receive [ChangeEvent]s when the text is changed;
 * the source object for the events will be the text component
 */
fun JTextComponent.addChangeListener(changeListener: ChangeListener) {
    val dl: DocumentListener = object : DocumentListener {
        private var lastChange = 0
        private var lastNotifiedChange = 0
        override fun insertUpdate(e: DocumentEvent) = changedUpdate(e)
        override fun removeUpdate(e: DocumentEvent) = changedUpdate(e)
        override fun changedUpdate(e: DocumentEvent) {
            lastChange++
            SwingUtilities.invokeLater {
                if (lastNotifiedChange != lastChange) {
                    lastNotifiedChange = lastChange
                    changeListener.stateChanged(ChangeEvent(this))
                }
            }
        }
    }
    addPropertyChangeListener("document") { e: PropertyChangeEvent ->
        (e.oldValue as? Document)?.removeDocumentListener(dl)
        (e.newValue as? Document)?.addDocumentListener(dl)
        dl.changedUpdate(null)
    }
    document?.addDocumentListener(dl)
}

你可以在任何文本组件上使用它,如下所示:

myTextField.addChangeListener { event -> myEventHandler(event) }

就像他的代码一样,也是公有领域。

一种优雅的方法是将侦听器添加到插入符号位置,因为每次键入/删除内容时它都会更改,然后只需将旧值与当前值进行比较。

String oldVal = ""; // empty string or default value
JTextField tf = new JTextField(oldVal);

tf.addCaretListener(e -> {
    String currentVal = tf.getText();

    if(!currentVal.equals(oldVal)) {
        oldVal = currentVal;
        System.out.println("Change"); // do something
    }
});

(此事件也被触发每次用户只是点击进入TextField)。

向底层Document中添加侦听器,底层Document是自动为您创建的。

// 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);
     }
  }
});

它是Codemwnci的更新版本。他的代码很好,除了错误信息外,其他方面都很好。为了避免错误,必须更改条件语句。

  // 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);
     }
  }
});
textBoxName.getDocument().addDocumentListener(new DocumentListener() {
   @Override
   public void insertUpdate(DocumentEvent e) {
       onChange();
   }

   @Override
   public void removeUpdate(DocumentEvent e) {
      onChange();
   }

   @Override
   public void changedUpdate(DocumentEvent e) {
      onChange();
   } 
});

但我不会仅仅将用户(可能是意外)在键盘上触碰的任何东西解析为Integer。你应该捕获抛出的任何异常,并确保JTextField不是空的。