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.
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.