How do i make each of the buttons highlight when i hover

Viewed 197

I'm trying to make the buttons highlight (by changing color) when i am hovering above them with my mouse. this is my code;

import javax.swing.JOptionPane;
final int BUTTON_WIDTH = 100;
final int BUTTON_HEIGHT = 50;

int buttonX = 0;
int COLOR = 150;

void setup() {
  size(800, 400);
}

void draw() {
  for (int i=0; i<=8; i++) {
    drawButtons();
    buttonX = buttonX+BUTTON_WIDTH;
  }
}

void drawButtons() {
  strokeWeight(2);
  fill(0, COLOR, COLOR);
  rect(buttonX, 0, BUTTON_WIDTH, BUTTON_HEIGHT);
 
}

I thought it would work if i add this ;

if(mouseX<BUTTON_WIDTH && mouseY<BUTTON_HEIGHT){
    COLOR = 255;
  }

It does not work though, i am trying to make the button highlight when the mouse is over it and the other buttons would remain unchanged.

1 Answers

Your condition in the draw (before drawing the buttons) is wrong. Here a correct version of your program :

final int BUTTON_WIDTH = 100;
final int BUTTON_HEIGHT = 50;

int buttonX = 0;

void setup() {
  size(800, 400);
  strokeWeight(2);
}


void draw() {
  for (int i=0; i<=8; i++) {
    
    // The condition was wrong before, now it checks if you are on a button
    if(buttonX <= mouseX && mouseX < buttonX + BUTTON_WIDTH && mouseY<BUTTON_HEIGHT){
      fill(0, 255, 255);
    } else {
      fill(0, 150, 150);
    }

    rect(buttonX, 0, BUTTON_WIDTH, BUTTON_HEIGHT);
    buttonX += BUTTON_WIDTH;
  }
  buttonX = 0; // don't forget to put buttonX at 0 after the for loop, or the next buttons drawn are going to be invisible (on the right of the canva) and you won't see the color change.
}

Now it should be ok !

Related