Stefan Rafa
Stefan Rafa

Reputation: 1

Timed color changing label

I have three labels and on every second one label to stop at a time like a slot machines, i putted a random colors to be displayed on the labels and plus on every label to show random color, with this code i get same colors on every label so i need help with the timing and with placing a random color on every label here is the code i have:

Color[] color = new Color[6];
Random rand = new Random();
int colorNumber;

final void setColor(int nc) {
    colorNumber = nc;
    w1.setBackground(color[colorNumber]); // label
    w2.setBackground(color[colorNumber]); // label
    w3.setBackground(color[colorNumber]); // label
}

void changeColor() {
    color[0] = Color.RED;
    color[1] = Color.GREEN;
    color[2] = Color.BLUE;
    color[3] = Color.YELLOW;
    color[4] = Color.BLACK;
    color[5] = Color.ORANGE;

    int nc;
    do {
        nc = rand.nextInt(color.length);
    } while (nc == colorNumber);
    setColor(nc);
}

and this is the button

private void spinBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
    w1.setOpaque(true);
    w2.setOpaque(true);
    w3.setOpaque(true);

    Timer timer;
    timer = new Timer(100, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            changeColor();
        }
    });
    timer.start();
}

Upvotes: 0

Views: 116

Answers (1)

dic19
dic19

Reputation: 17971

with this code i have i get same colors on every label

Yes, because you set the very same color to all the labels:

w1.setBackground(color[colorNumber]); // label
w2.setBackground(color[colorNumber]); // label
w3.setBackground(color[colorNumber]); // label

i need help with the timing and with placing a random color on every label

You just need to set different colors for each label. For example, by making these changes:

Color color = new Color[6] {
    Color.RED,
    Color.GREEN,
    Color.BLUE,
    Color.YELLOW,
    Color.BLACK,
    Color.ORANGE
}; // Initialize this array just once

Random rand = new Random();

final void setColor(int nc, JLabel label) {
    label.setBackground(color[nc]);
}

void changeColor() {
   // Generate a new random int for each label
   setColor(rand.nextInt(color.length), w1);
   setColor(rand.nextInt(color.length), w2);
   setColor(rand.nextInt(color.length), w3);
}

Upvotes: 2

Related Questions