Why doesn't the first button click work?

boolean onButton;
String buttonChoice;

void setup(){
  size(700,500);
  background(255);
}

void draw(){
  noStroke();
  button("Button One", 20,30,200,100,20, "button1");
  button("Button Two", width-220,30,200,100,20, "button2");
}

void button(String in, int x, int y, int Width, int Height, int radius, String name){
  if(mouseX >= x && mouseX <= x + Width && mouseY >= y && mouseY <= y + Height){
    fill(200);
    onButton = true;
    buttonChoice = name;
  }else{
    fill(150);
    onButton = false;
  }

  rect(x, y, Width, Height, radius);
  fill(0);
  textAlign(CENTER,CENTER);
  textSize(Height/3);
  text(in, x + Width/2, y + Height/2);
}

void dothis(){
  print("ok");
}

void mousePressed(){
  if(onButton){
    println("Hello");
  }
}
Tagged:

Answers

  • Answer ✓

    can't work.

    but tricky to spot

    don't set onButton to false in function button

    set it false only on the beginning of draw()

  • Answer ✓

    the result of button one gets overwritten by the result of button two

  • Thank you so much Chrisir. That worked perfectly. I need to do a little more digging in order to grasp exactly why that worked, but I'm sure I can rationalize it eventually. Thanks again

  • Answer ✓

    in the old version:

    Why doesn't the first button click work?

    the result "onButton" of "button one" gets overwritten by the result of button two. So first button / button one won't work.

    think about it: we run the function once, onButton gets true. The function button gets called again and no matter what the status of onButton is, it is set to false, because the 2nd button doesn't have the mouse.

    Thus the 2nd button works, but the first does not.

    solution

    To counter that, the function button is not allowed to set onButton to false

    Thus it works.

Sign In or Register to comment.