Ivan
Ivan

Reputation: 39

How do I create varied colors for buttons in Java GUI?

I'm using this code to create a series of buttons in Java GUI, exactly 20 buttons, that has 20 different colors. Somehow, however, I couldn't, and if I use this code, I would end up coloring all 20 buttons in one, same color. How do I color them all with different colors in each buttons? Thank you in advance. Note that from the code, I do not use listed array.

        setTitle("My Frame");
        setSize(500, 200);
        setLayout(new GridLayout(0, 5));

        int R = (int) (Math.random()*256);
        int G = (int) (Math.random()*256);
        int B = (int) (Math.random()*256);
        Color color = new Color(R, G, B);

        for (int i = 0; i < 20; i++)
        {
            JButton button = new JButton(Integer.toString(i));
            setBackground(color);
            add(button);
        }
        setVisible(true);

Upvotes: 0

Views: 84

Answers (2)

ZhaoGang
ZhaoGang

Reputation: 4915

        setTitle("My Frame");
        setSize(500, 200);
        setLayout(new GridLayout(0, 5));

        for (int i = 0; i < 20; i++)
        {
            int R = (int) (Math.random()*256);
            int G = (int) (Math.random()*256);
            int B = (int) (Math.random()*256);
            Color color = new Color(R, G, B);
            JButton button = new JButton(Integer.toString(i));
            setBackground(color);
            add(button);
        }
        setVisible(true);

Upvotes: 0

Theodoros Chatzigiannakis
Theodoros Chatzigiannakis

Reputation: 29213

The variables R, G, B, and subsequently color are assigned a random value once, before the loop for starts. Then, throughout the loop, they retain the same values, so you end up with the same color for all of your buttons.

Try creating a new Color value in each iteration of the loop:

for (int i = 0; i < 20; i++)
{
    int R = (int) (Math.random()*256);
    int G = (int) (Math.random()*256);
    int B = (int) (Math.random()*256);
    Color color = new Color(R, G, B);

    JButton button = new JButton(Integer.toString(i));
    setBackground(color);
    add(button);
}

Now each iteration of the loop gets its own different random value for R, G, B (and color).

Upvotes: 1

Related Questions