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?
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));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With