0

I am trying to use getText() method from a JTextFeild in an ActionListener attatched with it ... the problem is I don't have a reference that points to it ... that is I'm adding those textFeilds with in a loop that takes a string from arraylist and showing new textFeild , I searched the Internet trying to find a way to use getText() but it was pointless because I have no ref. on it , my question is how to get the text in the JTextFeild in this action Listener , and is there is any way to get a reference to this JTextFeild that the action performed on ????

 JTextField t;
 for(MyClass m: MyArraylist) {
     t=new JTextField(m.toString());
     t.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    System.out.println(getText());
                    }
                    });
      }

I have tried getText(); super.getText(); t.getTaxt(); and for sure it will not work because t always changes ,also i tried system.out.println(m.toString()); and does not work

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Does this answer your question? [How to Retrieve value from JTextField in Java Swing?](https://stackoverflow.com/questions/5752307/how-to-retrieve-value-from-jtextfield-in-java-swing) – Ranker Dec 10 '19 at 20:48

2 Answers2

0

you have to use the function from the object

t.getText()

see here

Ranker
  • 43
  • 7
0

You should get the source for the event and cast it to the TextField

t.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        TextField tf = (TextField) e.getSource();
        System.out.println(tf.getText());
    }
});
Sunil Dabburi
  • 1,442
  • 12
  • 18
  • I tested it. How did you test it? The action listener will only run when you press `Enter`. If you want the listener to run on every key press, you should use `KeyEventListener` – Sunil Dabburi Dec 10 '19 at 21:00