Search code examples
javaswingreferencejtextfieldgettext

getting refrence for JTextFeild in actionListener


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


Solution

  • 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());
        }
    });