Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java add ActionListener on a separate class

Heres what I want to do, one of the classes is for a JFrame which contains all JButtons, I want another class to listen for the actions made on the JFrame class. See the code below:

public class Frame extends JFrame{
    //all the jcomponents in here

}

public class listener implements ActionListener{
    //listen to the actions made by the Frame class

}

Thanks for your time.

like image 433
Ewen Avatar asked Dec 27 '22 19:12

Ewen


2 Answers

Just add a new instance of your listener to whatever components you want to listen. Any class that implements ActionListener can be added as a listener to your components.

public class Frame extends JFrame {
    JButton testButton;

    public Frame() {
        testButton = new JButton();
        testButton.addActionListener(new listener());

        this.add(testButton);
    }
}
like image 112
JeffS Avatar answered Jan 08 '23 03:01

JeffS


1. You can use Inner Class, or Anonymous Inner Class to solve this....

Eg:

Inner Class

public class Test{

 Button b = new Button();


 class MyListener implements ActionListener{

       public void actionPerformed(ActionEvent e) {

                    // Do whatever you want to do on the button click.
      } 

   }
}

Eg:

Anonymous Inner Class

public class Test{

     Button b = new Button();

     b.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

                        // Do whatever you want to do on the button click.
          } 


   });

    }
like image 22
Kumar Vivek Mitra Avatar answered Jan 08 '23 03:01

Kumar Vivek Mitra