How to add action on a button from a different class. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to add action on a button from a different class.

Am trying to improve my code on graph ical user interface, and i have been adviced to create a class implementing actionlistener separately from the class implementing the interface, not as an inner class. I have tried the implementation but am getting an error when i pass an instance of the class implementing actionlistener as a parameter of addActionPerformed on a button. I have tried my best to explain, hope am understood. If yes, my u guys help me here..

10th Feb 2019, 7:23 PM
Mamuya, Gilbert .W
Mamuya, Gilbert .W - avatar
2 Answers
+ 2
So does it mean no one in hear knows how to do this?
15th Feb 2019, 6:18 AM
Mamuya, Gilbert .W
Mamuya, Gilbert .W - avatar
+ 1
Here is the answer to this: For illustration, lets create a simple javax swing button in one class and add an action listener in a separate class. import javax.swing.*; public class MybuttonClass{ private JButton button = new JButton("My Button"); public static void main(String[] args){ new ButtonActionClass(button); } } Above is a class called Mybutton class with a private button named button. The my button class has a main function which calls the constructor of another class called ButtonActionClass, and pass the button variable as a parameter of the constructor. Now, how should the class to implement the action of button look like? See here import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ButtonActionClass implements ActionListener{ public ButtonActionClass(JButton button){ button.addActionListener(this); } @Override public void actionPerformed(ActionEvent evt){ //here goes code which should be executed when button is clicked } }
16th Aug 2019, 2:39 PM
Mamuya, Gilbert .W
Mamuya, Gilbert .W - avatar