随机颜色到几个jbuttons

时间:2015-11-19 02:55:18

标签: java swing random arraylist jbutton

我需要为16个jbuttons中的每一个分配一个随机颜色,我的代码当前的方式,我得到一个随机颜色,但所有16个jbuttons都有相同的颜色。我理解为什么会这样,但我不知道如何解决它。万分感谢

package code;

import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GameG implements Runnable {

    public static JButton jba;
    public static JPanel jp;

@Override
public void run(){

    JFrame jf = new JFrame("Keybricks");
    Random rnd = new Random();

    jp = new JPanel();

    jp.setLayout(new GridLayout(4, 1));

    jf.setSize(300, 600);
    jf.setVisible(true);
    jf.setResizable(false);
    jf.add(jp);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ArrayList<Color> colors = new ArrayList<>();

    colors.add(Color.RED);
    colors.add(Color.BLUE);
    colors.add(Color.GREEN);
    colors.add(Color.YELLOW);

    Color randomColor = colors.get(rnd.nextInt(colors.size()));

    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    ArrayList<Character> letters = new ArrayList<>(); {

    for (char c : alphabet.toCharArray()) {
          letters.add(c);
        }

    char randomLetter = letters.get(rnd.nextInt(letters.size()));

    ArrayList<JButton> buttons = new ArrayList<>();

    for (int i = 0; i < 16; i++){
        JButton jb = new JButton();
        buttons.add(jb);
        jp.add(jb);
    }

    JButton randomJButton = buttons.get(rnd.nextInt(buttons.size()));


    for (JButton button : buttons){
        button.setBackground(randomColor);
        button.setOpaque(true);
    }

1 个答案:

答案 0 :(得分:2)

您必须为每个按钮添加新生成的随机颜色。你拥有它的方式,你只生成一个随机颜色,并为每个按钮分配相同的随机颜色。

jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ArrayList<Color> colors = new ArrayList<>();

colors.add(Color.RED);
colors.add(Color.BLUE);
colors.add(Color.GREEN);
colors.add(Color.YELLOW);

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

ArrayList<Character> letters = new ArrayList<>(); {

for (char c : alphabet.toCharArray()) {
      letters.add(c);
    }

char randomLetter = letters.get(rnd.nextInt(letters.size()));

ArrayList<JButton> buttons = new ArrayList<>();

for (int i = 0; i < 16; i++){
    JButton jb = new JButton();
    buttons.add(jb);
    jp.add(jb);
}

JButton randomJButton = buttons.get(rnd.nextInt(buttons.size()));

for (JButton button : buttons){
    Color randomColor = colors.get(rnd.nextInt(colors.size())); // Get a new random color
    button.setBackground(randomColor);
    button.setOpaque(true);
}