Why multiple windows can't show sketch correctly?

I want to create multiple windows, one to interact (put slide bar in it) and other to show the sketch. Now I can draw line/rectangle/ellipse directly in the second window. When these things in another class and use the class in the second window, they won’t show correctly. Does the coordinate system different in another PApplet? How can I solve this?

MultiWindows sketch2; 
Rec rec1;

void settings() {
  size(400, 400);
}

void setup() {
  surface.setLocation(0, 0);
  surface.setTitle("Sketch 1");

  rec1 = new Rec(200, 200);
  sketch2 = new MultiWindows();
}

void draw() {
  background(255);
  stroke(255, 0, 0);
  rec1.display();
}


class MultiWindows extends PApplet {
  Rec rec2;

  MultiWindows() {
    super();
    PApplet.runSketch(new String[] {this.getClass().getSimpleName()}, this);
  }

  public void settings() {
    size(400, 400);
  }

  public void setup() {
    surface.setLocation(400, 0);
    surface.setTitle("Sketch 2");
    rec2 = new Rec(200, 200);
  }

  public void draw() {
    background(255);
    stroke(0, 255, 0);
    rec2.display(); // won't work
    rect(200, 200, 40, 40); // this works fine
  }
}


class Rec {
  int x, y, r;

  Rec(int x, int y) {
    this.x = x;
    this.y = y;
    r = (int)random(20, 40);
  }

  void display() {
    rectMode(CENTER);
    noFill();
    rect(x, y, r, r);
    r = (int)random(20, 40);
  }
}

And I see from Internet that only one window can use OPENGL renderer such as P2D/P3D, why this multi-window OpenGL example works fine?

rectMode(), noFill(), rect(), etc. are all methods from class PApplet:
http://Processing.GitHub.io/processing-javadocs/core/processing/core/PApplet.html

However, directly invoking them w/o using the dot . operator:

Implies that they act upon the sketch’s main PApplet instance.

If you need a class to act upon other PApplet instances you’re gonna need to request & store their reference.

This is your class Rec modified to demand a PApplet reference right on its constructor:

static class Rec {
  static final int MIN_DIAM = 20, MAX_DIAM = 40;

  PApplet p;
  int x, y;

  Rec(PApplet p, int x, int y) {
    this.p = p;
    this.x = x;
    this.y = y;
  }

  void display() {
    p.noFill();
    p.circle(x, y, p.random(MIN_DIAM, MAX_DIAM));
  }
}

Obviously you’re gonna need to pass a PApplet ref. via keyword this when creating a Rec object now:
rec1 = new Rec(200, 200); - - > rec1 = new Rec(this, 200, 200);
rec2 = new Rec(200, 200); - - > rec2 = new Rec(this, 200, 200);

BtW, in order to avoid inadvertently invoking other PApplet methods w/o the dot . operator, it’s a good idea to declare such classes w/ the keyword static:

class Rec { - - > static class Rec {
class MultiWindows extends PApplet { - - > static class MultiWindows extends PApplet {

1 Like

Thanks a lot, it helps.