所以我试图检查所选复选框的总数是否== 10.如果是这样,我想要禁用未被选中的其他复选框!这意味着用户只能选择10个复选框。
我在想一个循环遍历数组的for loop
,然后检查是否选中了一个复选框,然后将1添加到计数器。如果计数器达到10,我认为可能很容易禁用其余的复选框,但显然不是!
List<Checkbox> chkSongs = new ArrayList<Checkbox>();
String labels[] = {"songA", "songB", "songC", "songD", "songE",
"songF", "songG", "songH", "songI", "songJ", "songK", "songL", "songM",
"songN", "songO", "songP", "songQ", "songR", "songS", "songT"}
for (int i = 0; i < labels.length; i++) {
Checkbox checkbox = new Checkbox(labels[i]);
chkSongs.add(checkbox);
formPanel.add(checkbox);
}
答案 0 :(得分:1)
这是我在飞行中写的东西,但我认为它符合你的要求:
public class CheckBoxFrame extends JFrame {
public CheckBoxFrame() throws HeadlessException {
JPanel formPanel = new JPanel(new GridLayout(-1, 4));
List<Checkbox> chkSongs = new ArrayList<>();
String labels[] = {"songA", "songB", "songC", "songD", "songE",
"songF", "songG", "songH", "songI", "songJ", "songK", "songL", "songM",
"songN", "songO", "songP", "songQ", "songR", "songS", "songT"};
for (String label : labels) {
Checkbox checkbox = new Checkbox(label);
chkSongs.add(checkbox);
formPanel.add(checkbox);
}
CheckBoxListener listener = new CheckBoxListener(chkSongs, 10);
setContentPane(formPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
}
public class CheckBoxListener implements ItemListener {
private int boxesChecked;
private final List<Checkbox> checkBoxes;
private final int maxSelections;
public CheckBoxListener(List<Checkbox> checkBoxes, int maxSelections) {
this.checkBoxes = new ArrayList<>(Objects.requireNonNull(checkBoxes));
this.maxSelections = maxSelections;
this.boxesChecked = (int) this.checkBoxes.stream().filter(cb -> cb.getState()).count();
this.checkBoxes.forEach(cb -> cb.addItemListener(this));
}
@Override
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
boxesChecked++;
} else {
boxesChecked--;
}
if (boxesChecked == maxSelections) {
checkBoxes.stream().filter(cb -> !cb.getState()).forEach(cb -> cb.setEnabled(false));
} else if (boxesChecked == maxSelections - 1) {
checkBoxes.stream().forEach(cb -> cb.setEnabled(true));
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new CheckBoxFrame().setVisible(true);
}
});
}
}
这仍有其缺陷(例如,你可以将监听器添加到另一个复选框),但它并不太糟糕。
答案 1 :(得分:0)
使用'getState()'查看是否选中了复选框。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id ="sizeButton1" class="sizeButton" >S </div>
<div id ="sizeButton2" class="sizeButton" >M</div>
<div id ="sizeButton3" class="sizeButton" >L</div>