Hello everyone,
I tried to create a button class and now I am wondering what I can improve upon this code.
I am also wondering how I would be able to only have the upper button working when the buttons overlap each other. At the moment, both buttons will work then.
Button b1, b2, b3;
int Bsize = 150; //Button size
void setup() {
size(500, 500);
background(150);
b1 = new Button("-", #0A0A0A, width/2-100, height/2, Bsize, Bsize);
b2 = new Button("+", #0A0A0A, width/2+100, height/2, Bsize/2, Bsize);
b3 = new Button("B", #0A0A0A, width/2, height/2-100, Bsize, Bsize);
}
void draw() {
if (b1.MousePressed()) {
background(200, 200, 0);
}
if (b2.MousePressed()) {
background(150);
}
if (b3.MousePressed()) {
background(0, 200, 200);
}
b1.B_draw();
b2.B_draw();
b3.B_draw();
}
class Button {
int button_w, button_h, pm_size, posx, posy; //pm_size == the size of the built in + and - sign.
String T; //Text on the button.
color ct, cb; //ct = text color, cb = button color (cb gets his values from noSelect/Select)
color noSelect = #00B9FF; //Color when the button is not selected
color Select = #0081B2; //Color when the button is selected.
boolean Output;
Button(String Text, color cText, int x, int y, int w, int h) { //(Text on the button, color of the text, pos X, pos Y, width, height)
posx = x;
posy = y;
button_w = w;
button_h = h;
T = Text;
ct = cText;
cb = noSelect;
if( button_w > button_h){ //Checks what the smallest is: button_w or button_h. And gives the smallest value to pm_size.
pm_size = button_h;
}else if ( button_h > button_w){
pm_size = button_w;
}else if(button_w == button_h){
pm_size = button_h;
}
}
void B_draw() {
MousePressed();
pushMatrix();
translate(posx, posy);
strokeWeight(1);
fill(cb);
rectMode(CENTER);
rect(0, 0, button_w, button_h);
stroke(0);
strokeCap(SQUARE);
strokeWeight(pm_size/15);
if (T == "+") { //Build in + symbol to get a centered +
line(-pm_size/2.5, 0, pm_size/2.5, 0);
line(0, -pm_size/2.5, 0, pm_size/2.5);
} else if (T == "-") { //Build in - symbol to get a centered -
line(-pm_size/2.5, 0, pm_size/2.5, 0);
} else { //Display the custom text
fill(ct);
textAlign(CENTER, CENTER);
textSize(button_h);
text(T, 0, 0-(button_h/9));
}
popMatrix();
}
boolean MousePressed() { //Checks if the mouse is over the button
if (mouseY > posy-(button_h/2) && mouseY < posy+(button_h/2) && mouseX > posx-(button_w/2) && mouseX < posx+(button_w/2)) {
cb = Select;
if (mousePressed == true) { //Checks if the mouse is pressing the button
return true;
} else {
return false;
}
} else {
cb = noSelect;
return false;
}
}
}