event when I change size

edited April 2018 in How To...

Hi friends,

I'm using surface.setResizable(true); to can adapt the size of my window, it runs perfectly. I'm asking if there is an way to catch this event when I change the size with my mouse. I need to change the size of my PGraphics inside my sketch. Is it possible ?

Answers

  • Processing does not generate an event when the window is resized so you have to detect the change yourself. This code demonstrates how to do this.

    NOTE: the pre() is a special method that will be executed immediately before each call to draw() because we have registered it.

    int w, h;
    String ws = "";
    
    void setup() {
      size(400, 360);
      w = width;
      h = height;
      surface.setResizable(true);
      registerMethod("pre", this);
    }
    
    void pre() {
      if (w != width || h != height) {
        // Sketch window has resized
        w = width;
        h = height;
        ws = "Size = " +w + " x " + h + " pixels";
        // Do what you need to do here
      }
    }
    
    void draw() {
      background(200, 200, 255);
      fill(0);
      text(ws, 30, 30);
    }
    
  • Thxs for sharing @quark. Here is my example.

    Kf

    //REFERENCE: https://forum.processing.org/one/topic/detect-resize.html
    //REFERENCE: https://github.com/processing/processing/wiki/Library-Basics
    //REFERENCE: https://github.com/processing/processing/wiki/Window-Size-and-Full-Screen
    
    
    
    
    int w, h;
    String ws = "";
    PGraphics pg;
    
    void setup() {
      size(400, 360);
      w = width;
      h = height;
      surface.setResizable(true);
      registerMethod("pre", this);
    
      refreshPG();
    }
    
    void pre() {
      if (w != width || h != height) {
        // Sketch window has resized
        w = width;
        h = height;
        ws = "Size = " +w + " x " + h + " pixels";
        // Do what you need to do here
        refreshPG();
      }
    }
    
    void draw() {
      background(200, 200, 255);
      fill(0);
      text(ws, 30, 30);
      image(pg,width/3,height/3);
    }
    
    
    void refreshPG() {
      int ww=int(w/3.0);
      int hh=int(h/3.0);
    
      println("REFRESH ", ww, hh);
      pg=createGraphics(ww, hh, JAVA2D);
      pg.beginDraw();
      pg.background(random(100, 200));
      pg.endDraw();
    }
    
Sign In or Register to comment.