how to find source component that generated a DocumentEvent

前端 未结 3 1740
眼角桃花
眼角桃花 2020-12-05 19:27

Is it possible to discover which oject generated a DocumentEvent? Something like i can do with ActionListener:

JTextField field = new JTextField(\"\");
field         


        
相关标签:
3条回答
  • 2020-12-05 19:45

    You can set a property in the document to tell you which textcomponent the document belongs to:

    For example:

    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);
    

    Alternatively:

    Get the document that sourced the event and compare it to the document of the textfield.

    Example:

    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");
        }
    }
    
    0 讨论(0)
  • 2020-12-05 20:02

    Rather than add multiple fields to the same listener. Create a custom listener that upon creation takes a reference to the text field. Then create a new instance of the listener each time you add it to a field.

    0 讨论(0)
  • 2020-12-05 20:06

    The attempt with the document property is equivalent to an independent

    Map<javax.swing.text.Document, javax.swing.JTextField> textFields;
    

    The suggested extension of the listener could be

    public void bind(JTextField tf)
    {
        final Document doc = tf.getDocument();
        textfields.put(doc, tf);
        doc.addDocumentListener(this);
    }
    
    0 讨论(0)
提交回复
热议问题