Run code on exit (follow-up)

edited November 2015 in Questions about Code

This is a follow-up of the thread: http://forum.processing.org/one/topic/run-code-on-exit.html

The recommended method for running some code when closing the sketch used to be registering a dispose handler. However, it looks like the registerDispose() method from PApplet is deprecated (see Javadoc)

The following code still works but is there a recommended alternative to the registerDispose() method?

public class DisposeHandler {

DisposeHandler(PApplet pa)
{
  pa.registerDispose(this);
}

public void dispose()
{      
  println("Closing sketch");
}

}

Answers

  • Answer ✓

    The new way of registering dispose (V2) is

    registerMethod("dispose", this);

  • edited October 2013

    Thanks quark!

    Here's the full code for later reference:

    
    DisposeHandler dh;
    
    void setup() {
        dh = new DisposeHandler(this);
        // setup stuff
    }
    
    void draw() {
        // draw stuff
    }
    
    public class DisposeHandler {
      
      DisposeHandler(PApplet pa)
      {
        pa.registerMethod("dispose", this);
      }
      
      public void dispose()
      {      
        println("Closing sketch");
        // Place here the code you want to execute on exit
      }
    }
    
  • Hi, This is great! It will help me solve for some serialEvent() crashes that I've been having. I see that the dispose() does not get called when closing from the IDE stop button. Is there a way to run code on that event? Or is it because of what NoahBuddy says on this thread? http://processing.org/discourse/beta/num_1240630170.html Basically that the JVM is not obligated to run the method, so it likely won't.

  • edited September 2016

    Another way to run code on exit:

    void exit() {
      //put code to run on exit here
      super.exit();
    }
    
Sign In or Register to comment.