How to interrupt JCheckBox by (yes/no) confirmation dialog to proceed or prevent the check?

210 Views Asked by At

Required scenario:

  • User checks the JCheckBox.
  • Check interrupted by (Yes/No) confirmation dialog box.
  • If Yes = proceed with visual check, and do other actions.
  • If No = prevent visual check, and do nothing.

Update: In case if user uncheck the box (which was previously checked), no confirmation dialog should appear.

SSCCE code:

This is my try, but I am not sure if it is the proper way of doing it. So if you know a better/proper way of doing it, please provide it

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class CheckBoxConfirm {

    JCheckBox checkBox;
    int count;

    private JPanel createPanel() {

        JPanel containerPanel = new JPanel();
        checkBox = new JCheckBox("Check me");
        checkBox.addItemListener(new CheckBoxListener());
        containerPanel.add(checkBox);
        return containerPanel;
    }

    class CheckBoxListener implements ItemListener {

        @Override
        public void itemStateChanged(ItemEvent event) {

            Object source = event.getSource();
            if (source == checkBox) {
                if (event.getStateChange() == ItemEvent.SELECTED) {
                    count += 1;
                    if (count == 1) {
                        int dialogResult = JOptionPane.showConfirmDialog(
                                null, "This will erase inputs.\nAre you sure?",
                                "Warning", JOptionPane.YES_OPTION);
                        if (dialogResult == JOptionPane.YES_OPTION) {
                            // Allow checkBox to be checked, and proceed other actions.
                            System.out.println("Selected");
                            count += 1;
                            checkBox.setSelected(true);
                        } else if (dialogResult == JOptionPane.NO_OPTION) {
                            System.out.println("Selection intrrupted");
                            // Prevent checkBox selection.
                        }
                    }
                } else if (event.getStateChange() == ItemEvent.DESELECTED && count == 0) {
                    System.out.println("Deselected");
                }
            }
            count = 0;
        }
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(() -> {
            CheckBoxConfirm cbc = new CheckBoxConfirm();
            JFrame frame = new JFrame("CheckBoxConfirm");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(cbc.createPanel());
            frame.pack();
            frame.setVisible(true);
        });
    }
}
0

There are 0 best solutions below