独自のコントローラーを作成して、1 つのセット内のすべてのボタンを一緒に関連付けることができます。
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
。これにより、一度に 1 つのボタンだけが選択されるようになります。
詳細については、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);
}
}
}
}
}