javaevent-handlingjcheckbox

Java JCheckBoxMenuItem fire event only when selected


I have a JCheckBoxMenuItem inside a JMenu. My task is simple: when it's selected, it should fire a DialogBox, in other words a JFileChooser. When it's unselected, do nothing. PROBLEM: it works fine when it's selected, but it keep doing the same when unselected.

This is the code:

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....
     });

I'm not sure where the issue is, maybe it's related to the action lister which is nested. It's fired even when the checkbox got unselected. Is there a way so solve this?


Solution

  • The issue is you are checking isSelected in wrong place. you should check the Selection inside actionPerformed.

    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....
                                }
                            }
                        };
                    });
                }
            });