Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

You actually are getting the PlainDocument object. Just store it in a variable instead of printing it.

For more info see docs.

What you need to do is adding document listners to each component you need.If you really need to know which text fields text has changed then you can have a property in the DocumentListner as textFieldName or something and you can set it when you create the document listner for them.But I think you better change your approaching to situation.It doesn't sound good.

You may update the document without knowing the context.

Consult the documentation of javax.swing.event.DocumentEvent

These methods combined with the document retrieved by javax.swing.event.DocumentEvent.getDocument() allow you to update the document in a proper way. Later you may add other text field without any change.

To simply get the text of a JTextField after change:

JTextField myTf = new ...; // maybe an attribute definition
...
myTf.addActionListener(
   new ActionListener(){@Override public void actionPerformed( ActionEvent e ) {
      JTextField tf = (JTextField)e.getSource();
      System.out.println( tf.getText());
      if( tf == myTf ) { // == for reference comparison
         ... // do something dedicated to myTf
      }
   }});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top