Search code examples
javaswingawtactionlistenerjtextfield

Java - change JTextField using separate ActionListener


I have two classes, A and B.

Class A has a JTextField, and a private variable of class B. Class B implements ActionListener.

Class A and B are in separate files. Can I access the JTextField from class B through the ActionListener or is there a way (it is a requirement that I cannot have class B contained in A) I can do it? I've been searching and I haven't found a solution yet.

Thanks for your time :)


Solution

  • In class B's actionPerfored method, you can access the source of the event through ActionEvent argument:

    public void actionPerformed(ActionEvent e){
        JTextField field = (JTextField)e.getSource();//Now should represent the JTextField in class A
    }
    

    You can then perform actions on the JTextField. I would be wary when using class B as an ActionListener for other components though as this would throw an Exception if the source is not a JTextField.