如何找到生成 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();
}
}
回答者应考虑以下几点:
The answser should take in consideration the following points:
- 就我而言,仅了解生成事件的对象类型是不够的,但我需要在运行时引用它.
- 通常,事件是从 Swing 对象的扩展(myComp 公共 JTextField)生成的.这些对象存储应在运行时在侦听器方法(如 insertUpdate)中检索的附加信息
- DocumentListener 是从不知道生成事件的字段的类中实现的.可以在运行时将不同类型的不同字段附加到侦听器.
推荐答案
可以在文档中设置一个属性来告诉你文档属于哪个文本组件:
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屋!
查看全文