当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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.

网友答案:

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");
                }
            });
        }
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: