我试图切换我的jcheckbox。 我已将默认值设置为检查jcb2。 我的jcb1工作正常,但我的jcb2似乎无法切换。 我添加了一个println,发现它被打印但我的jcb2没有得到检查。
class CheckBoxHandler implements ItemListener { public void itemStateChanged(ItemEvent e) { if(jcb1.isSelected()) { jcb1.setSelected(true); jcb2.setSelected(false); } if(jcb2.isSelected()) { jcb1.setSelected(false); jcb2.setSelected(true); System.out.println("1"); } } }im trying to toggle my jcheckbox. I have set the default to check jcb2. my jcb1 is working fine but my jcb2 can't seem to be toggled on. I added a println and found that it gets printed but my jcb2 does not get check.
class CheckBoxHandler implements ItemListener { public void itemStateChanged(ItemEvent e) { if(jcb1.isSelected()) { jcb1.setSelected(true); jcb2.setSelected(false); } if(jcb2.isSelected()) { jcb1.setSelected(false); jcb2.setSelected(true); System.out.println("1"); } } }最满意答案
如果选中了第一个复选框,则在您选择第二个复选框时将同时选中它们。 这意味着将满足第一个if ,以便立即取消选择第二个复选框。
因此,不应选中选中哪个复选框,而应使用ItemEvent e查看刚刚选中的复选框。
if(e.getStateChange() == ItemEvent.SELECTED) { if(e.getItem() == jcb1) { jcb2.setSelected(false); } else { jcb1.setSelected(false); } }If the first check-box is selected, they will both be selected the moment you select the second check-box. This means the first if-condition will be met, such that the second check-box will be deselected right away.
So instead of checking which check-boxes are selected, you should use the ItemEvent e to see which check-box you just selected.
if(e.getStateChange() == ItemEvent.SELECTED) { if(e.getItem() == jcb1) { jcb2.setSelected(false); } else { jcb1.setSelected(false); } }更多推荐
发布评论