i developed a simple image editor in java, how can i do to show a message dialog when i click exit on a JFrame to ask the user if he want to save the work?
thank's everybody
i developed a simple image editor in java, how can i do to show a message dialog when i click exit on a JFrame to ask the user if he want to save the work?
thank's everybody
Use a JOptionPane
showing up on a specific event. For example the window closing event in the WindowListener
.
WindowListener wl = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// add the option pane code here
}
};
JFrame yourFrame = // your frame here
yourFrame.addWindowListener(wl);
A JOptionPane
can be created as such:
final JOptionPane optionPane = new JOptionPane(
"The only way to close this dialog is by\n"
+ "pressing one of the following buttons.\n"
+ "Do you understand?",
JOptionPane.QUESTION_MESSAGE,
JOptionPane.YES_NO_OPTION);
Resulting option pane. Another alternative is to use one of the more specialized factory methods.
int option = JOptionPane.showConfirmDialog(null,"Exit Application?");
if(option == JOptionPane.YES_OPTION) {
System.exit(0);
}
When you add a new close handler like this i would suggest to deactivate the default handler using this code:
yourFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
For more information about the setDefaultCloseOperation
consult the documentation.
Hope this helps
Check out Closing an Application for basic information and examples.
You need to follow two basic steps:
WindowListener
to the frame and handle the windowClosing(...)
eventsetDefaultCloseOperation(...)
on the frame to allow the WindowListener to take control of the closing event.The above link shows a simple example as well as a simple API that does both of the above steps so all you need to do is create an Action
to handle your closing logic.