Closing a Sketch Window in Processing Java

| Sat May 22 2021 | edited Sat May 22 2021

How to close a sketch window in Processing

I have been creating various projects in Processing, and a few of my projects required me to create a popup window (A new sketch.)

Generally, Processing just closes your program when a sketch is closed, and doesn't focus much on disposing the window properly, which makes it hard to create and close new sketch windows. Here are some ways to do that.

In my examples, I was using Processing 4, but this should apply to Procesing 3 as well.

First things first, override the exitActual() method:

class Example extends PApplet {

  public void exitActual() {
    // nothing needed here

This prevents Processing from closing your program when this sketch is closed.

Here is where things get a bit more complicated.

Depending on which renderer you are using, specific steps are required.


Table of Contents

Java2D (default)

In general, the default renderer will not need any extra code to close properly. In one of my cases, I had some problems, so I will post the code I used which seemed to solve my problem.

import processing.awt.PSurfaceAWT;
import processing.core.PApplet;
import processing.core.PSurface;
import javax.swing.*;

class Java2D extends PApplet {

  public void exit() {
    dispose();    // these two
    super.exit(); // may not be necessary
    PSurface surface = getSurface();
    PSurfaceAWT.SmoothCanvas smoothCanvas = (PSurfaceAWT.SmoothCanvas) surface.getNative();
    JFrame frame = (JFrame) smoothCanvas.getFrame();


P2D or P3D

For the P2D/P3D renderer, trying to close the sketch without doing anything resulted in the program hanging. I was not able to find a good way to close the sketch. Instead, I used this hack:

import com.jogamp.nativewindow.WindowClosingProtocol;

class P2DorP3D extends PApplet {

  public void exit() {
    // calling a bunch of methods to try and dispose of the window
    surface.setVisible(false); // actually hides the window
    throw new RuntimeException("thrown purposely!"); // if the "x" is pressed, this line by itself also closes the window
  // See sources at bottom of page for where I got this from!
  public void setup() {
    if (getGraphics().isGL()) {
      final com.jogamp.newt.Window w = (com.jogamp.newt.Window) getSurface().getNative();


Throwing a RuntimeException gets caught by the graphics library and closes the window successfully!

I haven't figured out the magic behind why throwing errors closes the OpenGL sketches yet, but if I figure it out, I'll update this page.

Helpful Links / Sources


Add a comment