Hey guys! I’m just experimenting with how to code a system that selects one from multiple buttons in your sketch if clicked on one button and deselects it when clicked on another button so that always just one or none button is selected.
I’ve coded so far a program that creates 3 buttons as an object in a button class that can be pressed and highlighted. But my problem is that it doesn’t deselect the button when I click another button.
Here is my code so far:
(the integer “numberOfButtons” sets the number of buttons in the sketch)
int numberOfButtons = 3;
int selectedButton;
int index = 0;
int buttonNumber;
Button[] btns;
class Button {
int buttonNumber;
float a, b, c, d;
boolean selected;
color selectedColor, defaultColor, currentColor;
String label;
Button(float a, int b, float c, float d, String label, int buttonNumber) {
this.buttonNumber = buttonNumber;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.label = label;
selected = false;
selectedColor = 150;
defaultColor = 225;
currentColor = defaultColor;
}
void display() {
for (int i = 0; i < numberOfButtons; i++) {
noStroke();
fill(currentColor);
rect(a, b, c, d);
fill(0);
textAlign(CENTER, CENTER);
textSize(50);
text(label, a+c/2, b+d/2);
}
}
void select(int mx, int my) {
if (selectedButton == buttonNumber) {
selected = !selected;
if (selected && selectedButton == buttonNumber) {
currentColor = selectedColor;
} else if (!selected && selectedButton == buttonNumber) {
currentColor = defaultColor;
}
}
}
void click() {
if (overButton(a, b, c, d)) {
selectedButton = buttonNumber;
}
}
boolean overButton(float x, float y, float sizeX, float sizeY) {
if (mouseX >= x && mouseX <= x+sizeX &&
mouseY >= y && mouseY <= y+sizeY) {
return true;
} else {
return false;
}
}
}
void setup() {
background(25);
fullScreen();
btns = new Button[numberOfButtons];
index = 0;
for (int i = 0; i < numberOfButtons; i++) {
btns[index++] = new Button(width/10, 200*index, width*0.8, height/12, ""+index, index);
}
}
void draw() {
background(25);
for (Button btn : btns) {
btn.display();
}
fill(255);
}
void mouseClicked() {
for (Button btn : btns) {
btn.click();
btn.select(mouseX, mouseY);
}
}
Can someone tell me what is going on and, perhaps, how to fix and/or improve it?
Greetings