您可以像这样创建一个按钮组:
public class SingleSelectionButtonGroup {
private final List<JButton> buttons;
public static SingleSelectionButtonGroup group(List<JButton> buttons) {
return new SingleSelectionButtonGroup(buttons);
}
public static SingleSelectionButtonGroup group(JButton...buttons) {
return new SingleSelectionButtonGroup(Arrays.asList(buttons));
}
private SingleSelectionButtonGroup(List<JButton> buttons) {
this.buttons = new ArrayList<JButton>(buttons);
setupListener();
}
private void setupListener() {
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
SingleSelectionButtonGroup.this.disableAllExcept((JButton) e.getSource());
}
};
for (JButton button : buttons) {
button.addActionListener(listener);
}
}
private void disableAllExcept(JButton clickedButton) {
for (JButton button : buttons) {
if (!clickedButton.equals(button)) {
button.setEnabled(false);
}
}
}
}
然后将它与要分组的按钮集合一起使用:
public class Application {
public void run() {
final JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(400, 300));
final JPanel pane = new JPanel();
List<JButton> buttons = new ArrayList<JButton>();
String[] texts = {"A", "B", "C"};
for (String text : texts) {
JButton button = new JButton(text);
buttons.add(button);
pane.add(button);
}
SingleSelectionButtonGroup.group(buttons);
frame.getContentPane().add(pane);
frame.setVisible(true);
}
public static void main(String[] args) {
new Application().run();
}
}