lundi 21 août 2023

I'm trying to change the color of some of the blocks in my grid every 2 seconds

I'm trying to change the color of some of the blocks in my grid every 2 seconds. So far, the blocks are just a set color (yellow), but I need them to automatically and randomly change color repetitively. This is the code so far; g is the grid.

g.setColor(Color.yellow);
g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
g.setColor(Color.black);

I tried using a random generator:

private static final int MIN_STATE_COLOR = STATE_RED;
private static final int MAX_STATE_COLOR = STATE_YELLOW;

int random = new Random().nextInt(MAX_STATE_COLOR - MIN_STATE_COLOR + 1) + MIN_STATE_COLOR;

g.setColor(Color.random);
g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
g.setColor(Color.black);

And that gave me an error with MIN_STATE_COLOR and MAX_STATE_COLOR.

I then also tried creating a timer:

ActionListener timerListener = new ActionListener() {
  public void actionPerformed(ActionEvent evt) {
    g.setColor(Color.red);  // I don't know how to make it random
    g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
    g.setColor(Color.black);
  }
};
int timerDelay = 3 * 1000;
Timer timer = new Timer(timerDelay, timerListener);

But this also gave me an error.




Aucun commentaire:

Enregistrer un commentaire