views:

68

answers:

2
public void itemStateChanged(ItemEvent event)
{
    if(event.getSource() == doctorBox)
    {
        if (doctorBox.isSelected() == true)
            JOptionPane.showMessageDialog(null, "you are a doctor");
        else if (doctorBox.isSelected() != true)
            JOptionPane.showMessageDialog(null, "you are not a doctor");
    }
}

when the application is run... the checkbox is by default unchecked when I check the "doctorBox" ... I get two dialog boxes popping together: "you are a doctor" and "you are not a doctor", also the checkbox doesn`t get checked!

why does that happen? how do I change the code to work correctly?

+1  A: 

Here are some great samples. Remove all CheckBoxes except one and make sure you have a single listener to a single CheckBox per the details at the provided link. My guess is that there is strangeness occurring due to the way in which the listeners have been added in conjunction with the CheckBoxes.

Aaron
Neither the awt CheckBox nor the JCheckBox have an isChecked method, both use either getState() or isSelected().
josefx
@josefx Yeah I edited answer...I had my .NET hat on
Aaron
+1  A: 

Couple things to help you

for your logic, Since you know that the choice is either on or off, try the following

if(doctorBox.isSelected())
  //do something
else
  //do something else

with the checkbox not getting selected, change from an ItemListener to an ActionListener.

private class aListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(e.getSource() == doctorBox){
                if(doctorBox.isSelected())
                     JOptionPane.showMessageDialog(null, "you are a doctor");
                else {
                     JOptionPane.showMessageDialog(null, "you are not a doctor");
                }
            }   
        }
    }

If you look at your current code, and step through it using a debug you will see that your ItemListener gets fired 2 times. The first time checks it, the 2nd time it unchecks it. All on a single click. I cant explain the inner working of an itemListener in this case. ActionListener works much better

Sean