processing and controlP5 - Button broken when Size is set to value of variable

447 Views Asked by At

In the following code, I am trying to create 3 buttons the scale with the shown image. The problem that occurs is, the buttons don't change color when the mouse hovers over them and the button press events are not working. If I set the size of the buttons to a fixed value instead of the value of a variable everything works fine. Does anybody know why this happens or how I can achieve the scaling some other way?

Here my code:

import controlP5.*;

ControlP5 cp5;

int bg = color(255, 255, 255);

int bSX, bPY;

Button BrTP;

class playground extends Canvas {
  int c1 = color(105, 130, 157);
  int c2 = color(117, 144, 174);
  PImage img = loadImage("bg.png");
  
  void setup(PApplet a) {
    
  }
  
  void draw(PGraphics g) {
    g.image(img, 10, 10, img.width, img.height);
  }
}

void setup() {
  size(400, 400);
  noStroke();
  
  surface.setResizable(false);
  cp5 = new ControlP5(this);
  
  playground canv = new playground();
  canv.pre();
  surface.setSize(canv.img.width+20, canv.img.height+80);
  surface.setLocation((displayWidth - canv.img.width-20) / 2, (displayHeight - 65 - canv.img.height-80) / 2);
  cp5.addCanvas(canv);
  
  bSX = (canv.img.width - 20) / 3; // buttonSizeX
  bPY = canv.img.height + 20; // buttonPositionY
  
  BrTP = cp5.addButton("randomTP").setValue(0).setPosition(10, bPY).setSize(bSX, 50);
  cp5.addButton("safeTP").setPosition(20 + (canv.img.width - 20) / 3, canv.img.height + 20).setSize(bSX, 50);
  cp5.addButton("wait").setPosition(30 + 2 * (canv.img.width - 20) / 3, canv.img.height + 20).setSize(bSX, 50);
}

void draw() {}

public void controlEvent(ControlEvent e) {
  println(e.getController().getName());
}

public void randomTP(int val) {
  println("rTP:"+val);
}

The result looks like this: Screenshot of the Window

1

There are 1 best solutions below

0
On BEST ANSWER

I found a fix myself, although I don't understand why it works. Solution: In my code I am changing the window size two times: first time here size(400, 400); and second time here surface.setSize(canv.img.width+20, canv.img.height+80);. The click detection will only work inside the area set by size(), thus if a button is on the border, only the part inside the area will work and if it is completely outside it won't work at all.

Fix:

size(displayWidth, displayHeight);

Edit: for some reason I can't accept the answer. It says I have to wait 2 days.