通常的答案是“使用 DocumentListener
”。但是,我总是发现该界面很麻烦。说实话,界面被过度设计了。它有三种方法,用于插入,删除和替换文本,当它只需要一种方法时:替换。(插入可以被视为用某些文本替换无文本,删除可以被视为替换某些没有文本的文本。
通常,您只需要知道框中的文本何时发生更改,因此典型的实现具有三个调用一个方法的方法。DocumentListener
因此,我制作了以下实用程序方法,该方法允许您使用更简单的ChangeListener
而不是.(它使用Java 8的lambda语法,但如果需要,您可以将其适应旧的Java。DocumentListener
/**
* 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);
}
与直接向文档添加侦听器不同,这处理在文本组件上安装新文档对象的(不常见)情况。此外,它解决了Jean-Marc Astesana答案中提到的问题,即文档有时会触发比需要的更多的事件。
无论如何,此方法允许您替换如下所示的烦人代码:
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());
代码发布到公共领域。玩得愉快!