Why is PGraphics.g2 null

I’m having trouble rendering PShapes into a PGraphics object. Here is the simplest version of the code that demonstrates the issue:

PGraphics g;

void setup() {
  size(850, 850);
  g = createGraphics(800, 800);
  PShape s = createShape(RECT, 100,100,500,500);
  g.shape(s);
}

void draw() {
  background(250);
  image(g, 25, 25);
}

Running this code produces the following error:
java.lang.NullPointerException: Cannot invoke "java.awt.Graphics2D.setStroke(java.awt.Stroke)" because "this.g2" is null

Why is this happening please?

The problem is because you didn’t mark the start and end of draw for the PGraphics. This is the way to do it

PGraphics g;

void setup() {
  size(850, 850);
  
  g = createGraphics(800, 800);
  g.beginDraw();
  PShape s = createShape(RECT, 100,100,500,500);
  g.shape(s);
  g.endDraw();
}

void draw() {
  background(250);
  image(g, 25, 25);
}

Also I suggest that you use pg instead of g as PApplet has an attribute of the same name, at least it used to :grinning:

1 Like

Hello @Rico,

Some references related to this:

:)

@quark was faster! :running_man: But here’s my take on it: :stuck_out_tongue:

PGraphics pg;
PShape ps;

void setup() {
  size(800, 600);
  imageMode(CENTER);
  noLoop();

  fill(#0000FF); // blue
  stroke(#FFFF00); // yellow
  strokeWeight(3.5);

  pg = createGraphics(width >> 1, height >> 1);
  ps = createShape(RECT, 50, 50, pg.width - 100, pg.height - 100);

  pg.beginDraw();
  pg.background(#FF0000); // red
  pg.shape(ps);
  pg.endDraw();
}

void draw() {
  background(#008000); // lime
  image(pg, width >> 1, height >> 1);
}

Thanks all, I’ve marked GoToLoop’s as the solution, but Quark’s wad just as good.