[英]Why does insertUpdate get called in my DocumentListener when I change focus? (Java Swing)
我有一個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搖擺不應該通過更改焦點來觸發文檔偵聽器事件...
您必須有一些東西在關注焦點,否則您就認為它正在點火,而事實並非如此。
我接受了您的代碼並制作了一個完整的示例,它沒有您描述的問題。
JFrame frame = new JFrame();
final JTextField numPlotRowsJTextField = new JTextField(3);
numPlotRowsJTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
numPlotRowsJTextField.setBackground(Color.cyan);
}
@Override
public void removeUpdate(DocumentEvent e) {
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 100);
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new JTextField(2));
frame.getContentPane().add(numPlotRowsJTextField);
frame.setVisible(true);
您是否查看過DocumentEvent來查看其中包含的信息? 它實際上是否包含已更改的字符串。 還是僅僅是一個長度為0的字符串的事件。 如果是后者,那么也許您可以忽略這種情況。
我想到了。 100%與JGoodies Binding有關。
此代碼有效:
ValueModel valueModelNumberPlotRowsJTextField = adapter.getBufferedModel("numberOfPlotRows");
valueModelNumberPlotRowsJTextField.addValueChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt)
{
numPlotRowsJTextField.setBackground(Color.cyan);
}
});
numPlotRowsJTextField = BasicComponentFactory.createIntegerField(valueModelNumberPlotRowsJTextField);
因為我使用的是JGoodies綁定,所以我有一個ValueModel支持我的JTextField。 偵聽器必須在此處設置,而不是在JTextField上設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.