Search code examples
javaswingjoptionpane

Setting a default close action in JOptionPane


How can I set the red 'X' button to close the application? I know how to do it within a JFrame, but I don't know how to set it in a JOptionPane.

At the moment, clicking the red 'X' initializes the game instead of exiting the application.

JOptionPane.showMessageDialog(null, panel, "Let's Play!", JOptionPane.QUESTION_MESSAGE, icon);

Solution

  • Use a ConfirmDialog. Depending on the action, you get different values (-1, 0, 1).

    int i = JOptionPane.showConfirmDialog(null, "Test", "test", JOptionPane.YES_NO_OPTION);
    System.out.println(i);
    

    The "X" returns -1, "Yes" returns 0 and "No" returns 1. Now you can choose whether the game should start depending on the value