Java JCheckBoxMenuItem 仅在选中时触发事件

Java JCheckBoxMenuItem fire event only when selected

我在 JMenu 中有一个 JCheckBoxMenuItem。 我的任务很简单:当它被选中时,它应该触发一个 DialogBox,换句话说就是一个 JFileChooser。当它未被选中时,什么也不做。 问题:它在被选中时工作正常,但在未被选中时它会继续做同样的事情。

这是代码:

JCheckBoxMenuItem checkBox = new JCheckBoxMenuItem("ChebkBox");
    checkBox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent arg0) {
            if(checkBox.isSelected())
            {
                System.out.println("SELECTED!");
                checkBox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        JFileChooser fileChooser = new JFileChooser();
                        if (fileChooser.showSaveDialog(checkBox) == JFileChooser.APPROVE_OPTION) {
                            //DIALOG BOX CODE....
     });

我不确定问题出在哪里,可能与嵌套的动作列表器有关。即使取消选中复选框,它也会被触发。 有办法解决这个问题吗?

问题是您在错误的地方检查了 isSelected。 您应该检查 actionPerformed 中的 Selection。

checkBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent arg0) {
                System.out.println("SELECTED!");
                checkBox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        if (checkBox.isSelected()) {
                            if (fileChooser.showSaveDialog(checkBox) == JFileChooser.APPROVE_OPTION) {
                                // DIALOG BOX CODE....
                            }
                        }
                    };
                });
            }
        });