Search code examples
javajoptionpane

Returning if the user hits the x in the top corner of a JOptionPane.showMessageDialog


JOptionPane.showMessageDialog(null, roll, "Dice Game", JOptionPane.INFORMATION_MESSAGE, die);

When I run this, I want to know if the user hits x so I can change a boolean, roll is a JTextArea, die is an image icon, null is my layout.

The problem is the showMessageDialog is a void method. So I can't check. Thanks.

I do not have a JFrame nor do I want one.


Solution

  • ShowMessageDialog is not designed for this. It is used to display a message, not to get user feedback. You should use a showConfirmDialog for your purpose, with OK_CANCEL_OPTION because it is really what you want: clicking on the X button is like using a Cancel button.

    If you really do not want a Cancel button, then you have to create your own JDialog actually you can use JOptionPane.showOptionDialog:

    int result = JOptionPane.showOptionDialog(null, roll, "Dice Game", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, die, new Object[] { "OK"}, null);
    

    result will be 0 if the user press OK, and -1 if the user close the dialog with the X button.