如何查找生成DocumentEvent的源组件 [英] how to find source component that generated a DocumentEvent
本文介绍了如何查找生成DocumentEvent的源组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能发现哪个项目生成了DocumentEvent?我可以用ActionListener做的事情:
Is it possible to discover which oject generated a DocumentEvent? Something like i can do with ActionListener:
JTextField field = new JTextField("");
field.addActionListener(actionListener);
//inside ActionListener
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() instanceof JTextField) //true
}
我想对DocumentEvent做同样的事情,但似乎不会以同样的方式工作:
I would like to do the same with DocumentEvent but seems not to work the same way:
JTextField field = new JTextField("");
field.getDocument.addDocumentListener(documentListener);
//inside documentListener
public void insertUpdate(DocumentEvent){
if (arg0.getSource() instanceof JTextField) //false: class is javax.swing.text.PlainDocument
if (arg0.getSource() instanceof MyComponent){
MyComponent comp = (MyComponent)arg0.getSource();
comp.callSpecificMethodUponMyComp();
}
}
答案者应该考虑以下几点: / p>
The answser should take in consideration the following points:
- 为了我的目的,知道生成事件的对象类型是不够的,但我需要在运行时引用它。
- 通常,事件是从swing对象的扩展(myComp public JTextField)生成的。这些对象存储应在运行时在侦听器方法内检索的其他信息(例如,插入更新)
- DocumentListener是从不知道生成事件的字段的类实现的。不同类型的不同字段可以在运行时附加到侦听器。
推荐答案
您可以设置文档中的属性告诉您文档属于哪个textcomponent:
You can set a property in the document to tell you which textcomponent the document belongs to:
例如:
final JTextField field = new JTextField("");
field.getDocument().putProperty("owner", field); //set the owner
final JTextField field2 = new JTextField("");
field2.getDocument().putProperty("owner", field2); //set the owner
DocumentListener documentListener = new DocumentListener() {
public void changedUpdate(DocumentEvent documentEvent) {}
public void insertUpdate(DocumentEvent documentEvent) {
//get the owner of this document
Object owner = documentEvent.getDocument().getProperty("owner");
if(owner != null){
//owner is the jtextfield
System.out.println(owner);
}
}
public void removeUpdate(DocumentEvent documentEvent) {}
private void updateValue(DocumentEvent documentEvent) {}
};
field.getDocument().addDocumentListener(documentListener);
field2.getDocument().addDocumentListener(documentListener);
另外:
获取发起事件的文档并将其与文本字段的文档进行比较。
Get the document that sourced the event and compare it to the document of the textfield.
示例:
public void insertUpdate(DocumentEvent documentEvent) {
if (documentEvent.getDocument()== field.getDocument()){
System.out.println("event caused by field");
}
else if (documentEvent.getDocument()== field2.getDocument()){
System.out.println("event caused by field2");
}
}
这篇关于如何查找生成DocumentEvent的源组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文