切换JCheckBox值(Toggling JCheckBox value)

系统教程 行业动态 更新时间:2024-06-14 16:57:18
切换JCheckBox值(Toggling JCheckBox value)

我试图切换我的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); } }

更多推荐

本文发布于:2023-04-12 20:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/a2e85d004b278b6defb4dc5220ede799.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JCheckBox   Toggling

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!