Search code examples
javaclassbuttonprocessingfill

Checklist in processing fill problems


So I have this checklist code in processing, and I want to be able to click one of the buttons in the list, and have that button fill itself black, but each time. I got that part working for a single button, but whenever I implement more buttons in the class and click a button, it fills every single button. I've tried using pushMatrix/popMatrix & pushStyle/popStyle, but every time I do that, the buttons never change color when I click them. If someone could tell me how to do that, that would be much appreciated.

Here's the button class:

class Button {
// Other optional attributes could be r, g, and b values for examples
int xLoc;
int yLoc;
int wide;
int tall;
int fill;
boolean checked;

Button(int x, int y, int w, int h, int f) {
xLoc = x;
yLoc = y;
wide = w;
tall = h;
fill = f;
}

void display() {
//fill with blue green and create the rect 
fill(fill);
if (mousePressed) {
  if (button1.isClicked() == true) {
    fill = 0;
  }
}
ellipse(xLoc, yLoc, wide, tall);
}

// returns true if the mouse is over the button and false otherwise
boolean isClicked() {
if (mouseX > xLoc && mouseX < xLoc + wide) {
  if (mouseY > yLoc && mouseY < yLoc + tall) {
    return true;
  }
}
return false;
}

boolean isChecked() {
if (fill == 0) {
  return true;
} else {
  return false;
}
}
}

And here is the main code:

Button button1 = new Button(50, 50, 20, 20, 255);
Button button2 = new Button(50, 75, 20, 20, 255);
Button button3 = new Button(50, 100, 20, 20, 255);
Button button4 = new Button(50, 125, 20, 20, 255);

void setup() {
size(500, 500);
}

void draw() {
background(50);
button1.display();
button2.display();
button3.display();
button4.display();
}

Solution

  • The pushMatrix and popMatrix() functions only deal with translations and rotations. They don't deal with fill colors.

    Look at this line in your Button class:

    if (button1.isClicked() == true) {
    

    Every single button is checking only if button1 is clicked. You probably want that to be checking whether the current button is clicked:

    if (isClicked() == true) {
    

    Which can be shortened to this:

    if (button1.isClicked()) {