简体   繁体   English

JOptionPane出现在选定的JCheckBox上

[英]JOptionPane to appear on selected JCheckBox

Hi all I am having some difficulties with adding a joptionpane in JcheckBox listener 大家好我在JcheckBox监听器中添加joptionpane时遇到了一些困难


public void itemStateChanged(ItemEvent evt) {

            if(evt.getStateChange() == ItemEvent.SELECTED){
                    ///some code

                        JOptionPane.showMessageDialog(null,  "Message", "Alert",
                                JOptionPane.INFORMATION_MESSAGE);
            }
    }

so it works fine,but the problem is that the JCheckBox gets selected and immediately deselected how can I manage to fix this ? 所以它工作正常,但问题是JCheckBox被选中并立即取消选择我如何设法解决这个问题?

Cheers 干杯

The problem must be in "///some code" as the following test program works for me in Java 6: 问题必须在“/// some code”中,因为以下测试程序适用于Java 6:

public class CheckBoxItemListener {
    public static void main(String[] args) {
        final JCheckBox checkBox = new JCheckBox("Click me");

        JFrame frame = new JFrame("CheckBox Item Listener");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 300, 300);
        frame.add(checkBox);
        frame.setVisible(true);

        checkBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent evt) {
                if (evt.getStateChange() == ItemEvent.SELECTED){
                    JOptionPane.showMessageDialog(null,  "Message", "Alert",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
    }
}

Have a look in the omitted code for setSelected or doClick calls. 查看setSelected或doClick调用的省略代码。

There are a couple of suggestions here (solution) to use an action listener instead of a item listener. 这里有一些建议(解决方案)来使用动作侦听器而不是项侦听器。 This does work, however, I though it strange given that all the texts I have suggest an item listener is the expected type of listener for a check box. 这确实有效,但是,我觉得很奇怪,因为我建议项目监听器的所有文本都是复选框的预期监听器类型。

In fact, this is a known bug as acknowledged by Oracle Bug ID:6924233 The JOptionPane apparently causes another event to be generated. 事实上,这是一个已知的错误,如Oracle Bug ID所承认:6924233 JOptionPane显然会导致生成另一个事件。

The recommended fix is to invoke the JOptionPane using invokeLater. 建议的修复方法是使用invokeLater调用JOptionPane。 This works fine and involves only a minor code change to a program already using an item listener for other purposes. 这样可以正常工作,并且仅对已经使用项侦听器用于其他目的的程序进行少量代码更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM