class not working as intended
in
Programming Questions
•
8 months ago
Hello I am trying to create this class, that creates a button and when clicked changes the color of it. But the way I am doing it is not working, can you tell me what is wrong og tell me another way to achieve the same?
Thanks in advance
- Button b1 = new Button(1, "Grayscale");
- Button b2 = new Button(2, "Grayscale");
- void setup()
- {
- size(500, 350);
- textAlign(CENTER, CENTER);
- }
- void draw() {
- b1.display();
- b2.display();
- }
- class Button {
- boolean selected = false;
- int nr, x, y, w, h;
- String name;
- Button (int nr, String inName) {
- name = inName;
- w = 70;
- h = 20;
- x = nr*(w+10)-w;
- y = 350-(h+10);
- }
- void display() {
- if (selected) fill(255, 0, 0);
- else fill(150);
- rect(x, y, w, h);
- fill(0);
- text(name, x+(w/2), y+(h/2));
- }
- void mousePressed() {
- if (mouseX > x && mouseX < x+w && mouseY > y && mouseY < y+h && selected == false) {
- selected = true;
- }
- else if (mouseX > x && mouseX < x+w && mouseY > y && mouseY < y+h && selected == true) {
- selected = false;
- }
- }
- }
1