This shows how you can use the inner class :
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JRadioButton; public class TestInnerClass { JRadioButton radioOne = new JRadioButton(); JRadioButton radioTwo = new JRadioButton(); JRadioButton radioThree = new JRadioButton(); Object myObject = new Object(); public TestInnerClass() { ActionListener myInnerClass = new MyActionListener(); radioOne.addActionListener(myInnerClass); radioTwo.addActionListener(myInnerClass); radioThree.addActionListener(myInnerClass); } private class MyActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent event) { if(radioOne.isSelected()) myObject.toString(); else if(radioTwo.isSelected()) myObject.notify(); else if(radioThree.isSelected()) myObject.getClass().getName(); } } }
- Note that the inner class is not static, as stated in the gontard comment, therefore it is visible to myObject. And itβs safer to keep it secret.
It is often useful for one listener to handle all events, as in this case. However, there are other cases where you want your event handling to be more specific to each component. For example, in these cases, radioThree may trigger an event, and since these buttons are not part of a group, it is possible that RadioOne is still in the selected state. This single handler will fire and act only on the first radio. Although one way to fix this would be to add checks for the source, as in:
public void actionPerformed(ActionEvent event) { if(event.getSource() == radioOne && radioOne.isSelected()) myObject.toString(); if(event.getSource() == radioTwo && radioTwo.isSelected()) myObject.notify(); if(event.getSource() == radioThree && radioThree.isSelected()) myObject.getClass().getName(); }
Another way is to use one listener for each component. That the anonymous class is very convenient:
radioOne.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { myObject.doOne(); } });
One of my favorite patterns, especially if the work is nontrivial, is to first create a method to do the work, and then call it from the listener. I also end the call in SwingUtilities.invokeLater () to get work from the Swing event stream.
public class Test { JRadioButton radioOne = new JRadioButton(); Object myObject = new Object(); private void handleRadioOne() { myObject.toString();
This provides two nice features:
- It encapsulates your work in a method that allows programmatic access, if desired later
- It ensures that this method will work from the Swing event flow, so your GUI will not freeze during heavy processing.
source share