对此,通常的答案是“使用DocumentListener“然而,我总是觉得接口很麻烦。事实上,界面设计过度了。它有三种方法,用于插入、删除和替换文本,而它只需要一种方法:替换。(插入可以被看作是将没有文本的文本替换为某些文本,而删除可以被看作是对一些文本的替换,而不是文本。)
通常你只想知道当方框中的文本发生更改时,所以典型的DocumentListener实现有三个方法调用一个方法。
因此,我创建了以下实用程序方法,它允许您使用更简单的ChangeListener而不是DocumentListener..(它使用Java 8的lambda语法,但如果需要,可以将其用于旧Java。)/**
* Installs a listener to receive notification when the text of any
* {@code JTextComponent} is changed. Internally, it installs a
* {@link DocumentListener} on the text component's {@link Document},
* and a {@link PropertyChangeListener} on the text component to detect
* if the {@code Document} itself is replaced.
*
* @param text any text component, such as a {@link JTextField}
* or {@link JTextArea}
* @param changeListener a listener to receieve {@link ChangeEvent}s
* when the text is changed; the source object for the events
* will be the text component
* @throws NullPointerException if either parameter is null
*/public static void addChangeListener(JTextComponent text, ChangeListener changeListener) {
Objects.requireNonNull(text);
Objects.requireNonNull(changeListener);
DocumentListener dl = new DocumentListener() {
private int lastChange = 0, lastNotifiedChange = 0;
@Override
public void insertUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
changedUpdate(e);
}
@Override
public void changedUpdate(DocumentEvent e) {
lastChange++;
SwingUtilities.invokeLater(() -> {
if (lastNotifiedChange != lastChange) {
lastNotifiedChange = lastChange;
changeListener.stateChanged(new ChangeEvent(text));
}
});
}
};
text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
Document d1 = (Document)e.getOldValue();
Document d2 = (Document)e.getNewValue();
if (d1 != null) d1.removeDocumentListener(dl);
if (d2 != null) d2.addDocumentListener(dl);
dl.changedUpdate(null);
});
Document d = text.getDocument();
if (d != null) d.addDocumentListener(dl);}
与直接将侦听器添加到文档不同,这处理了在文本组件上安装新文档对象的情况(不常见)。此外,它还可以解决本文中提到的问题。阿斯特萨纳的回答,文档有时会触发比所需的事件更多的事件。
无论如何,此方法允许您替换如下所示的烦人代码:someTextBox.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
doSomething();
}
@Override
public void removeUpdate(DocumentEvent e) {
doSomething();
}
@Override
public void changedUpdate(DocumentEvent e) {
doSomething();
}});
有:addChangeListener(someTextBox, e -> doSomething());
发布到公共域的代码。玩得开心!