当我改变焦点时,为什么在我的 DocumentListener 中调用 insertUpdate? (Java 摇摆)
我有一个 JTextField ,上面有一个 documentListener 。当我向该文本字段添加或删除字符时,我想更改背景颜色。我应该使用文档侦听器,正确吗?它有效,但当我获得和失去对该 JTextfield 的焦点时,它也会触发,这是不希望的。我没有在此 JTextField 上添加焦点侦听器。这是我的代码,关于如何解决我的问题有什么建议吗?
numPlotRowsJTextField = BasicComponentFactory.createIntegerField(valueModelNumberPlotRowsJTextField);
numPlotRowsJTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e)
{
}
@Override
public void insertUpdate(DocumentEvent e)
{
numPlotRowsJTextField.setBackground(Color.cyan);
}
@Override
public void changedUpdate(DocumentEvent e)
{
}
});
另请注意,我正在使用 JGoodies Binding,我开始相信这是此问题的根源。不带 JGoodies 的 Swing 不应该通过改变焦点来触发文档侦听器事件...
I have a JTextField with a documentListener on it. I want to change the background color when I add or remove characters to this textfield. I should be using a document listener correct? It works, but it also fires when I gain and lose focus on this JTextfield, which is undesired. I do not add a focus listener on this JTextField. Here is my code, any suggestions on how I can fix my problem?
numPlotRowsJTextField = BasicComponentFactory.createIntegerField(valueModelNumberPlotRowsJTextField);
numPlotRowsJTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent e)
{
}
@Override
public void insertUpdate(DocumentEvent e)
{
numPlotRowsJTextField.setBackground(Color.cyan);
}
@Override
public void changedUpdate(DocumentEvent e)
{
}
});
Also note that I am using JGoodies Binding which I am starting to believe is the root of this problem. Swing w/o JGoodies shouldn't be firing off document listener events by changing focus...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须有某个东西正在注视焦点,否则您认为它正在发射,但实际上却没有。
我拿了你的代码并做了一个完整的例子,它没有你描述的问题。
You must have something looking at the focus or you think it is firing and it is not.
I took your code and made a complete example and it does not have the problem you describe.
您是否查看过 DocumentEvent 以了解它包含哪些信息?它实际上包含已更改的字符串吗?或者它只是一个长度为 0 的字符串的事件。如果是后者,那么也许你可以忽略这种情况。
Have you looked at the DocumentEvent to see what information it contains? Does it actually contain a string that has changed. Or is it just an event with a 0 length string. If it is the latter then maybe you can just ignore that case.
我想通了。这 100% 与 JGoodies Binding 有关。
此代码有效:
由于我使用 JGoodies Binding,因此我有一个支持 JTextField 的 ValueModel。侦听器必须在那里设置,而不是在 JTextField 上。
I figured it out. It 100% had to do with JGoodies Binding.
This code works:
Since I am using JGoodies Binding, I have a ValueModel backing my JTextField. The listener has to be set there and not on the JTextField.