Software Dev
Software Dev

Reputation: 1102

JOptionPane Dialog Determine if Close Button was Clicked

I want to create a dialog with a checkbox and a combobox. This is what I have:

JCheckBox checkBox = new JCheckBox("My checkbox");

JLabel modeLabel = new JLabel("Select mode:");
String[] modes = {"A", "B", "C"};
JComboBox<String> modesComboBox = new JComboBox<>(modes);
JPanel modePanel = new JPanel(new FlowLayout());
modePanel.add(modeLabel);
modePanel.add(modesComboBox);

JPanel dialogPanel = new JPanel();
dialogPanel.setLayout(new BoxLayout(dialogPanel, BoxLayout.Y_AXIS));
dialogPanel.add(checkBox);
dialogPanel.add(modePanel);

JOptionPane.showMessageDialog(null, dialogPanel);

How do I determine whether the Close (i.e., "X") button or the OK button was clicked? I need to know which one of these two buttons caused the dialog to close.

Upvotes: 0

Views: 935

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168845

Use JOptionPane.showConfirmDialog(Component,Object) (or overloaded equivalents) to get an int returned that reports yes, no or cancelled.

Calling showConfirmDialog..

Brings up a dialog with the options Yes, No and Cancel; with the title, Select an Option.
Parameters:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used
message - the Object to display
Returns:
an integer indicating the option selected by the user

Edit

On closer inspection, it becomes apparent this task needs both a confirmation dialog and an option dialog. Here is a complete example that reports the results of the user choices to the console.

import javax.swing.*;

public class OptionSelection {

    public OptionSelection() {
        int result;
        String[] modes = {"A", "B", "C"};
        result = JOptionPane.showOptionDialog(
                null,
                "Modes",
                "Select mode",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null,
                modes,
                "B"
        );
        if (result == JOptionPane.CLOSED_OPTION) {
            System.out.println("User canceled mode selection");
        } else {
            System.out.println("Result: " + modes[result]);
        }
        result = JOptionPane.showConfirmDialog(null,
                "Are you now, or have you ever?",
                "Declaration",
                JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
            System.out.println("User says YES!");
        } else if (result == JOptionPane.NO_OPTION) {
            System.out.println("User says NO!");
        } else {
            System.out.println("User canceled");
        }
    }

    public static void main(String[] args) {
        Runnable r = () -> new OptionSelection();
        SwingUtilities.invokeLater(r);
    }
}

Upvotes: 4

Related Questions