Reputation: 969
The goal of my code is to get the user input and when the user would like to save the data, they press the OK option. However, if the user has input some data, and would no longer like to continue, they then just press the red cross exit button via the top right corner to exit without saving?
How do I go about this?
Here's my code:
JOptionPane.showMessageDialog(null, myPanel, "Edit Fruit", JOptionPane.INFORMATION_MESSAGE);
...
if (!(JOptionPane.OK_OPTION))
{
//If the user exits the option pane via the red cross, exit the loop.
break;
}
EDIT: This code does not work as I'm only looking for when a JOptionPane.showMessageDialog
is closed via the red cross and not an OK button:
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e)
{
System.out.println("Closed");
e.getWindow().dispose();
}
});
The code still executes even when I press the OK option in my JOptionPane. I only want to listen for the exit via the red cross.
Thanks for your help.
Upvotes: 1
Views: 1655
Reputation: 12728
Another quick search with the keywords "JOptionPanel close listener" takes me to another question.
How can I add a listener on the ok button of JOptionPane?
The accepted answer suggests to check the return value of the method showOptionDialog
.
But you can use the method
JOptionPane.showOptionDialog
with a singleDEFAULT_OPTION
for the OK button. TheshowOptionDialog
will return0
if OK was clicked and-1
if the user closed the dialog.int res = JOptionPane.showOptionDialog(null, "Hello", "Test", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null, null); System.out.println(res);
You don't need a listener because the javadoc says:
Each showXxxDialog method blocks the caller until the user's interaction is complete.
Here, there is no difference between close with rea cross, with key combinations, etc., as the first answer suggests. But, I guess maybe you don't need.
Upvotes: 1
Reputation: 49311
Firstly, it's not a very standard UI to do something only if the user closes a window by the red x - as opposed to closing the window by typing Alt-F4, or double clicking the icon, or Alt-Space-C, and so on; so I'll assume you just meant closing without pressing the OK button rather than by the red x specifically.
You have code which can detect when the window is closed.
You have code can detect when the user presses the OK button.
So set a flag to indicate the OK button was pressed, and if the flag is not set when the window closed, then the user closed the window without pressing the OK button.
Upvotes: 3