您可以编写自己的控制器,将单个集合中的所有按钮关联在一起,例如...
ButtonSetController controller = ButtonSetController(
checkBox1,
checkBox2,
checkBox3,
checkBox4,
checkBox5);
控制器会ActionListener
为每个按钮添加一个并监视那里的状态变化。当发生适当的状态更改时,控制器将能够自动禁用集合中的所有其他按钮...
public void actionPerformed(ActionEvent evt) {
JCheckBox btn = (JCheckBox)evt.getSource();
if (btn.isSelected()) {
for (JCheckBox cb : buttons) {
if (cb != btn) {
cb.setSelected(false);
cb.setEnabled(false);
}
}
} // Consider re-enabling all the buttons...?
}
现在,如果你也使用按钮数组,这一切都会变得更简单......
您也可以考虑添加按钮ButtonGroup
,这将确保在任何时候只选择一个按钮。
有关详细信息,请参阅如何使用 ButtonGroup 组件
作为一个粗略的例子
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ButtonControllerExample {
public static void main(String[] args) {
new ButtonControllerExample();
}
public ButtonControllerExample() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JCheckBox[] buttons = new JCheckBox[8];
buttons[0] = new JCheckBox("Bananas");
buttons[1] = new JCheckBox("Grapes");
buttons[2] = new JCheckBox("Apples");
buttons[3] = new JCheckBox("Pears");
buttons[4] = new JCheckBox("Kikiw");
buttons[5] = new JCheckBox("Potatos");
buttons[6] = new JCheckBox("Tomatoes");
buttons[7] = new JCheckBox("Tim Tams");
ButtonController<JCheckBox> controller = new ButtonController<>(4, buttons);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
for (JCheckBox cb : buttons) {
frame.add(cb);
}
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ButtonController<T extends JToggleButton> {
private List<T> selected;
private int limit;
public ButtonController(int limit, T... buttons) {
if (limit <= 0) {
throw new IllegalArgumentException("Limit can not be equal to or less then 0");
}
this.limit = limit;
selected = new ArrayList<>(limit + 1);
ItemStateHandler handler = new ItemStateHandler();
for (T btn : buttons) {
btn.addItemListener(handler);
}
}
public class ItemStateHandler implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
T btn = (T)e.getSource();
if (!selected.contains(btn) && btn.isSelected()) {
selected.add(btn);
while (!selected.isEmpty() && selected.size() > limit) {
btn = selected.remove(0);
btn.setSelected(false);
}
} else {
selected.remove(btn);
}
}
}
}
}