简体   繁体   English

困惑的复选框问题

[英]Confusing checkbox issue

I have a couple of checkboxes and 2 counters... counter1 counts how many of the checkboxes are checked with the following code 我有几个复选框和2个计数器... counter1计算使用以下代码检查了多少个复选框

if (isChecked) {
    counter++;
} else {
    counter--;
}

This works like a charm but now i want that counter2 keeps track of the checked checkboxes that belong to the "green" group... for example checkbox 1, 2, 4 and 7 belong to the " green" group and checkbox 3, 5, 6, 8 not. 这就像一个魅力,但现在我希望counter2跟踪属于“绿色”组的选中复选框...例如复选框1,2,4和7属于“绿色”组和复选框3,5 ,6,8不。

if (chk1.isChecked() || chk2.isChecked() || chk4.isChecked() || chk7.isChecked()) {
    counter2++;
}

I tried to use another if else to see how much of the "green" group are checked But when I use 我尝试使用另一个if else看看有多少“绿色”组被检查但是当我使用时

System.out.println(counter2);

then I always get the the value of counter1 . 然后我总是得到counter1的值。 Why is this happening? 为什么会这样? Is it because counter1 checks for all checked boxes and overrules counter2 ? 是因为counter1检查所有选中的复选框并counter2

int counter2 = 0; // reset counter    
for (Checkbox chk : allCheckboxes)  
    {   
       if (chk.isChecked() && isGreen(chk)) {
           counter2++;
       }  
    }   
    //...

and utilily method 和实用的方法

private boolean isGreen(Checkbox chk)  
{  
 // return true is checkbox is green  
}

As stated above in a comment, you check once if any of the boxes is checked. 如上面评论中所述,如果选中任何一个框,则检查一次。 If the counter2 always shows the same value as counter1, that could be the result of a simple typo or something. 如果counter2总是显示与counter1相同的值,那可能是一个简单的拼写错误的结果。 Impossible to say without seeing your code. 没有看到你的代码就不可能说。 But a variable can not just overrule another variable. 但变量不能仅仅否定另一个变量。

Are you using Swing and JCheckBox ? 你在使用SwingJCheckBox吗? If so, you can add an ItemListener to it, if you don't have one already. 如果是这样,你可以添加一个ItemListener ,如果你还没有。 Then you can dynamically update your counter to reflect the current state of your checkboxes. 然后,您可以动态更新计数器以反映复选框的当前状态。 The code for the itemStateChanged method could look something like this: itemStateChanged方法的代码可能如下所示:

public void itemStateChanged(ItemEvent arg0) {
    if (arg0.getStateChange() == ItemEvent.DESELECTED) { 
        counter--;
    } else {
        counter++;
    } 
    // update label or something
}



You can use a different ItemListener for your green group , which additionally sets counter2 . 您可以为绿色组使用不同的ItemListener ,另外还设置counter2
This frees you from all the iterative checking. 这使您免于所有迭代检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM