user4022167
user4022167

Reputation:

Save Checkbox state in a Panel/Dialog

I am new to swings and I have one doubt:

I have one dialog box, in that dialog, there is one Check Box, Ok and Cancel buttons. suppose user selected checkbox and click ok button, when user opens again that dialog box, the check box should be as selected.

can anyone give idea, how to implment this.

I know I can do this by using setSelected(true) and setSelected(false) methods.

but how to save the state of the check box.

Upvotes: 1

Views: 1392

Answers (1)

icza
icza

Reputation: 417777

You can pass components to the JOptionPane and they will be displayed properly.

So for example if you create a JCheckBox and pass it to the JOptionPane, after the dialog is closed, you can examine the state of the check box and store it anywhere you'd like to. Next time you want to display the dialog, before passing the check box, set its state to the one you stored last time.

For example (just for demonstration purposes):

final JFrame f = new JFrame("Checkbox test");
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
    // I store the checkbox state here in a boolean variable:
    boolean save;

    @Override
    public void windowClosing(WindowEvent e) {
        // Now user wants to close the application, ask confirmation:
        // We create a check box with the initial value of the stored state:
        JCheckBox cb = new JCheckBox("Save settings before Exit", save);
        int res = JOptionPane.showConfirmDialog(null,
            new Object[] {"Are you sure you want to Exit?", cb}, "Exit?",
                    JOptionPane.OK_CANCEL_OPTION);

        // Dialog closed, you can save the sate of the check box
        save = cb.isSelected();
        if (res == JOptionPane.OK_OPTION) {
            if (save) {
                // Settings can be saved here.
            }
            // And exit (by disposing the only frame)
            f.dispose();
        }
    }
});
f.getContentPane().add(new JLabel("Try to close the application"));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);

Upvotes: 1

Related Questions