How can I create a new PGraphics without having access to an existing PGraphics?

According to

To create a new graphics context, use the createGraphics() function. Do not use the syntax new PGraphics().

I have a place in my code where I need to create a PGraphics, but it is not in a place where I have access to an existing PGraphics on which to call createGraphics(). What can I do?


  • edited February 2018

    To be clear, this place is not inside any of PApplet's methods (e.g. draw()).

  • Here's a thing I've figured out how to do. I gave my subclass of PApplet a static property pointing to my instance of my subclass of PApplet. I then created a static method on my subclass of PApplet that gets a new PGraphics from that referenced instance. Now I can write

    // Processing is the name of my subclass of PApplet.

    PGraphics aNewPGraphics = Processing.createPGraphics(width, height);

    I feel like this is really kludgy, though. I still wonder if there's a better way.

  • If you're inside the Processing editor in the sketch, you can just call the createGraphics() function directly.

    If you're inside something like a .java class in a new tab, then you have to pass your sketch in and use that as a reference. This is exactly how you'd use functions like ellipse() and fill().

    class MyClass{
      private PApplet sketch;
      public MyClass(PApplet sketch){
        this.sketch = sketch;
      public void whatever(){
        PGraphics myGraphics = sketch.createGraphics();

    Then in your main sketch, you'd use the this keyword to pass a reference to the sketch into the class:

    MyClass myClass = new MyClass(this);
Sign In or Register to comment.