javaprocessingpgraphics

Processing: Get position of PGraphics object


Hi I need to make some widgets with Processing, for which I'm considering wrapping things together with a customized subclass of PGraphics. Then I'll be able to drag them around.

The current problem is, how do I get the position of a PGraphics object?

PGraphics widg;
void setup(){
  widg=createGraphics(50,50);
  drawWidg();
  image(widg,10,10);
}
void draw(){

}
void mouseClicked(){
  //PGraphics doesn't have x, y properties. How to get the position of widg?
  if(mouseX-widg.x>0 && mouseX-widg.x<widg.width && mouseY-widg.y>0 && mouseY-widg.y<widg.height){  
    println("clicked!");
  }
}
void drawWidg(){
  widg.beginDraw();
  ...
  widg.endDraw();
}

Solution

  • PGraphic doesn't have coordinates really, but you got to use some to display it, right? So those are yours coordinates. In the code above they would be (10,10) as used in the call to image() together with PGraphic width/height.

    And the code in mousePressed would be:

    void mouseClicked(){
       if(mouseX > 10 && mouseX < 10 + widg.width &&
          mouseY > 10 && mouseX < 10+ widg.height){  
        println("clicked!");
      }
    }
    

    Now this is not really good. As it has those hard numbers. So to avoid that you could use a PVector to store those positions like:

    PGraphics widg;
    PVector widgCoord;
    void setup(){
      widgCoord = new PVector(10, 10);
      widg=createGraphics(50, 50);
      drawWidg();
      image(widg,widgCoord.x, widgCoord.y);
    }
    void draw(){
    
    }
    void mouseClicked(){
       if(mouseX > widgCoord.x && mouseX < widgCoord.x + widg.width &&
          mouseY > widgCoord.y && mouseX < widgCoord.y + widg.height){  
        println("clicked!");
      }
    }
    
    
    void drawWidg(){
      widg.beginDraw();
      widg.background(255,0,0);
      widg.endDraw();
    }
    

    Or, as you mentioned, you could create a Widget class with a PGraphics, a PVector and what else you need. Something like:

    Widget one;
    
    void setup() {
      one = new Widget(10, 10, 50, 50);
      one.drawWidg();
    }
    void draw() {
      background(0);
      one.display();
    }
    void mouseClicked() {
      if (one.isOver()) { 
        println("clicked!");
      }
    }
    
    
    
    
    class Widget {
      PGraphics widg;
      PVector wCoord;
      color c = color(255, 0, 0);
    
      Widget(float x, float y, int w, int h) {
        wCoord = new PVector(x, y);
        widg = createGraphics(w, h);
      }
    
      void drawWidg() {
        widg.beginDraw();
        widg.background(c);
        widg.endDraw();
      }
    
    
      void display() {
        image (widg, wCoord.x, wCoord.y);
      }
    
      boolean isOver() {
        return mouseX > wCoord.x && mouseX < wCoord.x + widg.width &&
          mouseY > wCoord.y && mouseX < wCoord.y + widg.height;
      }
    }