Search code examples
javaswingeventsjcheckbox

JCheckBox deselects automatically


When I select the JCheckBox, it automatically deselects...

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Math extends JFrame 
{
    private JPanel panel2 = new JPanel();
    private JCheckBox cb = new JCheckBox("Record Answers");

    //Constructor
    public Math()
    {
        setSize(300,300);
        setTitle("Math");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        panel2.add(cb);

        //add ActionListners
        cb.addItemListener(new listenerCb());

        add(panel2, BorderLayout.SOUTH);            
        setVisible(true);
    }

    //itemListner for cb
    public  class listenerCb implements ItemListener
    {
        public void itemStateChanged(ItemEvent e)
        {       
            if(cb.isSelected())
            {
                JOptionPane.showMessageDialog(null,"Example");

            }
        }
    }
    public static void main(String[] args) 
    {
        new Math();

    }

 }

Whenever I try to select cb, it pops up the JOPtionPane and deselects. if I remove the JOptionPane, it works fine.


Solution

  • I think the problem is that the option pane is receiving some of the events because it now has focus.

    One solution is to wrap the code to display the JOptionPane in a SwingUtilities.invokeLater(...).

    This will allow the check mark to be repainted in its new state before the option pane is displayed.

    public  class listenerCb implements ItemListener
    {
        public void itemStateChanged(ItemEvent e)
        {
            if(cb.isSelected())
            {
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        JOptionPane.showMessageDialog(null,"Example");
                    }
                });
            }
        }
    }