Quote:how can i prevent the window closing and the sketch exit ?
It is hard to do because Processing sketches are applets, even if running on the desktop, and applets are probably not allowed to stop a browser or tab to be closed.
Maybe you can do some operations on exit, like showing dialog boxes, asking for a file name to save something, etc. but I believe you can't display something on the sketch's surface nor prevent closing.
Quote:i don't know the rule of super.stop()
The role of super.stop() is to call PApplet's stop() method, which clean up allocated resources, which can be important with some libraries (precisely to stop sound, to free com ports, etc.).
...
OK, I found a way to do whatever we want on closing the sketch.
By default, AWT frames do nothing when the system tries to close them (close button, close action on task bar's context menu, etc.). Processing has to tell to do a
System.exit(0) call upon this event to close the window. It does that by adding a window listener called on window closing.
So I had the idea to remove this window listener and putting my own...
Looks like:
Code:void ChangeWindowListener()
{
WindowListener[] wls = frame.getWindowListeners();
println("Found " + wls.length + " listeners");
if (wls.length > 0)
{
frame.removeWindowListener(wls[0]); // Suppose there is only one...
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
println("Should be closing!");
// Do something useful here
}
});
}
}
void draw()
{
if (frameCount == 1) // Important, before, listener isn't set
{
ChangeWindowListener();
}
// Your draw code
}
So you can ignore close requests altogether, although you should provide an alternative way to close the window to avoid angry users...
[EDIT] A simple example of confirmation:
[EDIT 2] Now also handling the Escape exit route...
Code:
void keyPressed()
{
// Do keyPressed stuff, if needed
// Also prevent direct exit from Escape key, ask confirmation first
if (key == KeyEvent.VK_ESCAPE)
{
key = 0;
ConfirmExit();
}
}
// Testing preventing accidental window closing...
void ChangeWindowListener()
{
WindowListener[] wls = frame.getWindowListeners();
//println("Found " + wls.length + " listeners");
if (wls.length > 0)
{
frame.removeWindowListener(wls[0]); // Suppose there is only one...
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
//println("Should be closing!");
ConfirmExit();
}
});
}
}
void ConfirmExit()
{
int exitChoice = javax.swing.JOptionPane.showConfirmDialog(frame,
"You have unsaved changes. Are you sure you want to exit?",
"SketchName - Confirm exit",
javax.swing.JOptionPane.YES_NO_OPTION
);
if (exitChoice == javax.swing.JOptionPane.YES_OPTION)
{
exit();
}
}