Search code examples
javaswingjcheckbox

JCheckBox: showMessageDialog twice in ItemStateChanged event


Why is my program calling showMessageDialog twice in ItemStateChanged event, even I put it in if else?

private void checkBox1ItemStateChanged(java.awt.event.ItemEvent evt) {                                           
    if(evt.getStateChange() == ItemEvent.SELECTED){
        //System.out.println("Check box 1 selected");
        JOptionPane.showMessageDialog(null, "Check box 1 selected");
    }
    else{
        //System.out.println("Check box 1 deselected");
        JOptionPane.showMessageDialog(null, "Check box 1 deselected");
    }
}    

If I only use System.out.println, the program will run correctly.


Solution

  • The state of the checkbox is not being updated before the JOptionPane is displayed. (Notice how the checkmark is not painted when the first option pane is displayed.

    So what you need to do is make sure the state is updated and repainted before displaying the JOption pane by using SwingUtilities.invokeLater(...) to display the JOptionPane:

    checkBox.addItemListener( new ItemListener()
    {
        public void itemStateChanged(java.awt.event.ItemEvent evt)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    if(evt.getStateChange() == ItemEvent.SELECTED)
                    {
                        JOptionPane.showMessageDialog(null, "Check box 1 selected");
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, "Check box 1 deselected");
                    }
                }
            });
        }
    });