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.
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);
}
}
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.
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With