We are about to switch to a new forum software. Until then we have removed the registration on this forum.
There may be a simple solution to this problem, but I just can't seem to solve it. The buttons each have a highlight feature. A boolean function is checking whether the mouse is over the button. But when the mouse is over "Button 1", "Button 2" is highlighted and vice versa. Seems like they are reversed or opposite. What can be wrong?
color rectColor = color(180); color rectHighlight = color(0); color baseColor = color(0); color baseColor1 = color(200); color currentColor = baseColor; int clk = 1; //times button clicked
ArrayList buttons;
void setup() { size (500, 300); smooth(); buttons = new ArrayList();
buttons.add(new Button("Button 1", 20, 20, 100, 50)); buttons.add(new Button("Button 2", 20, 100, 100, 50));
}
void draw() {
background(currentColor); for(int i = 0; i<2; i++){ Button b = buttons.get(i); b.showButton(); // draw the button in the window b.highlight(); // draw a highlight around the button if the cursor is over.
}
}
// mouse button clicked void mousePressed(){ for(int i = 0; i<2; i++){ Button b = buttons.get(i); b.mousePressed(); } }
class Button { String label; // button label float x; // top left corner x position float y; // top left corner y position float w; // width of button float h; // height of button
Button(String labelB, float xpos, float ypos, float widthB, float heightB) { label = labelB; x = xpos; y = ypos; w = widthB; h = heightB; }
void showButton() {
fill(rectColor);
stroke(rectHighlight);
rect(x, y, w, h,5);
textAlign(CENTER, CENTER);
fill(0);
text(label, x + (w / 2), y + (h / 2));
}
boolean mouseOver() { if (mouseX > x && mouseX < (x + w) && mouseY > y && mouseY < (y + h)) { return true; } return false; }
void highlight(){ if(mouseOver()) { rectHighlight = 255; } else { rectHighlight = 0; } }
void mousePressed(){ if(mouseOver()){ currentColor = rectColor;
print("Click: ");
println(clk++);
} } }
Answers
in draw()
also
explanation when the order of b.highlight(); and b.showButton(); is wrong,
the highlight is set at the end of draw and applied to the wrong button when you come into draw() again in the next loop
this is also because, these
are in global scope and not in the class
(which they should be I guess)
Thanks! That solved the problem - just by putting the variables in the class instead