是否有可能发现哪个对象生成了DocumentEvent?像我可以用ActionListener做的事情:
JTextField field = new JTextField(""); field.addActionListener(actionListener); //inside ActionListener public void actionPerformed(ActionEvent arg0) { if (arg0.getSource() instanceof JTextField) //true }
我想对DocumentEvent做同样的事情,但似乎不能以相同的方式工作:
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(); } }
回答者应考虑以下几点:
您可以在文档中设置一个属性,以告诉您该文档属于哪个文本组件:
例如:
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);
或者 :
获取引发事件的文档,并将其与文本字段的文档进行比较。
例:
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"); } }