Java adds ActionListener to a separate class

Here is what I want to do, one of the classes for the JFrame that contains all the JButtons, I want the other class to listen to the actions performed in the JFrame class. See 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 } 

Thank you for your time.

+4
source share
3 answers

Just add a new instance of your listener to the components you want to listen to. 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); } } 
+5
source

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

For instance:

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. } } } 

For instance:

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. } }); } 
+3
source

If you want the same listener instance to listen to all the buttons in the frame, you need to force the actionPerformed method to collect all clicks and delegate based on the command:

 public class listener extends ActionListener{ public void actionPerformed(ActionEvent e){ String command = e.getActionCommand(); if (command.equals("foo")) { handleFoo(e); } else if (command.equals("bar")) { handleBar(e); } } private void handleFoo(ActionEvent e) {...} private void handleBar(ActionEvent e) {...} } 

which will become easier in Java 7 where you can switch lines! Button click ActionCommand will be a JButton Text attribute unless you set it otherwise

+1
source

All Articles