Reputation: 109
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");
}
}
}
Upvotes: 1
Views: 2320
Reputation: 4878
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);
}
}
Upvotes: 4