Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get source object from DocumentListener (DocumentEvent)? [duplicate]

I have my class and I have implemented DocumentListener

public void removeUpdate( DocumentEvent arg0 ) {
   System.out.println( arg0.getDocument());
}

It would print javax.swing.text.PlainDocument@49ea903c

Is there any possible way I would get the object so I can get the value of the changed textfield? At the moment I have only one field so I do not need a check, but what if I use two or more, how do I know which JTextField has notified the listener?

like image 919
Nikola Avatar asked Sep 05 '26 00:09

Nikola


2 Answers

I'm not sure it's possible to get the swing component from a Document. But the issue is easily solved: just add a different instance of the listener to every text field, and store the text field in the listener itself.

textField1.getDocument().addDocumentListener(new MyDocumentListener(textField1));
textField2.getDocument().addDocumentListener(new MyDocumentListener(textField2));
textField3.getDocument().addDocumentListener(new MyDocumentListener(textField3));
like image 137
JB Nizet Avatar answered Sep 07 '26 14:09

JB Nizet


One option is to use an inner class, which will provide you an opportunity to reference the text field.

final JTextField field = new JTextField();

field.getDocument().addDocumentListener(new DocumentListener() {
  // Here you can reference 'field' in your methods
});

If you need to perform the same action for each text field, JB Nizet's solution will be neater.

like image 45
Duncan Jones Avatar answered Sep 07 '26 12:09

Duncan Jones