0

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263

1 Answers1

0

You can use this method (or if you want it done in one line this method) to generate a random color. Here is how you can use the first method in your case.

ActionListener timerListener = new ActionListener() {
    Random r = new Random();
    public void actionPerformed(ActionEvent evt) {
        Color c = new Color(
                r.nextFloat(),
                r.nextFloat(),
                r.nextFloat()
                );
        g.setColor(c);
        g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
        g.setColor(Color.black);
    }
};

And here is the second method

ActionListener timerListener = new ActionListener() {
    Random r = new Random();
    public void actionPerformed(ActionEvent evt) {
        g.setColor(new Color((int)(Math.random() * 0x1000000)));
        g.fillRect(wIncr * maxX / 2, 3 * hIncr, wIncr * (maxX / 2), hIncr * (maxY - 8));
        g.setColor(Color.black);
    }
};
  • I'm having the issue "Cannot refer to the non-final local variable g defined in an enclosing scopeJava(536870937)" because it's saying the grid is under : Graphics g - clubSimulation.ClubView.paintComponent(Graphics) – user21893624 Aug 22 '23 at 15:46
  • Refer [this question](https://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen) – Grinding For Reputation Aug 22 '23 at 16:44
  • To fix this make a field `Graphics g` then set the value of `g`(field) to `paintComponent(Graphics g)` using `this.g = g` – Grinding For Reputation Aug 23 '23 at 08:27