DocumentListener 出错 [英] Error with DocumentListener
问题描述
我有一个 JTextField,我希望将其限制为 15 个字符.问题是当我输入超过 15 个字符时,它会出错.我怎样才能解决这个问题?我必须使用其他对象吗?
I have a JTextField that I want to be limited to fifteen characters. The problem is that when I type over 15 characters, it errors. How can i fix this? Do I have to use some other object?
错误:线程AWT-EventQueue-0"中的异常java.lang.IllegalStateException:尝试在通知中发生变化
The error: Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
final int maxNicknameLength = 15;
final JTextField nickname = new JTextField(1); //Max length: 15
DocumentListener docListen = new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
lengthCheck(e, nickname, maxNicknameLength);
}
public void insertUpdate(DocumentEvent e) {
lengthCheck(e, nickname, maxNicknameLength);
}
public void removeUpdate(DocumentEvent e) {
lengthCheck(e, nickname, maxNicknameLength);
}
public void lengthCheck (DocumentEvent e, JTextField txt, int max) {
if (txt.getText().length() > max)
txt.setText(txt.getText().substring(0, max));
}
};
nickname.getDocument().addDocumentListener(docListen);
推荐答案
使用 DocumentFilter,而不是 DocumentListener.到侦听器触发时,文档已经更新.过滤器将阻止文档更新.
Use a DocumentFilter, not a DocumentListener. By the time the listener fires the Document has already been updated. A filter will prevent the document from being updated.
请参阅:实现文档过滤器工作示例可以满足您的需求.
See: Implementing a Document Filter for a working example that does what your want.
这篇关于DocumentListener 出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!