为了更进一步地了解 MadProgrammer 的建议 (1+),您可以为此目的使用 Swing Components 固有的 PropertyChangeSupport:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
@SuppressWarnings("serial")
public class RadioListenerTesterHFOE extends JPanel {
private RadioListenerHFOE radioListenerHfoe = new RadioListenerHFOE();
public RadioListenerTesterHFOE() {
add(radioListenerHfoe);
radioListenerHfoe.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getPropertyName().equals(RadioListenerHFOE.RADIO)) {
System.out.println("Radio Selected: " + pcEvt.getNewValue());
}
}
});
}
private static void createAndShowGui() {
RadioListenerTesterHFOE mainPanel = new RadioListenerTesterHFOE();
JFrame frame = new JFrame("RadioListenerTesterHFOE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class RadioListenerHFOE extends JPanel {
private static final String[] LABELS = {"1", "2", "3", "4"};
private static final int GAP = 5;
public static final String RADIO = "radio";
private ButtonGroup buttonGroup = new ButtonGroup();
private RadioListenerHandler handler = new RadioListenerHandler();
public RadioListenerHFOE() {
setLayout(new GridLayout(1, 0, GAP, 0));
for (String label : LABELS) {
JRadioButton radioButton = new JRadioButton(label);
radioButton.setActionCommand(label);
radioButton.addActionListener(handler);
buttonGroup.add(radioButton);
add(radioButton);
}
}
private class RadioListenerHandler implements ActionListener {
private String actionCommand = null;
@Override
public void actionPerformed(ActionEvent evt) {
setActionCommand(evt.getActionCommand());
}
private void setActionCommand(String actionCommand) {
String oldValue = this.actionCommand;
String newValue = actionCommand;
this.actionCommand = newValue;
firePropertyChange(RADIO, oldValue, newValue);
}
}
}