生成5种随机颜色,而不需要制作15个随机变量



我正在创建一个非常初级的Java程序,它创建了五个随机颜色和随机大小的面板(每个面板比下一个小)。

问题:当我的程序工作时,我必须为所有输入一个新变量。对于有3种颜色(R,G,B)的5个面板,我必须创建15个变量。难道就没有办法在(R,G,B)中调用随机而不是创建这么多变量吗?

下面是我的代码的摘录,它处理如何在每个面板中随机化颜色:

//Random Color Maker 1
Random rand = new Random();
int a = rand.nextInt(255);
int b = rand.nextInt(255);
int c = rand.nextInt(255);
    int d = rand.nextInt(255);
    int e = rand.nextInt(255);
    int f = rand.nextInt(255);
        int g = rand.nextInt(255);
        int h = rand.nextInt(255);
        int i = rand.nextInt(255);
            int j = rand.nextInt(255);
            int k = rand.nextInt(255);
            int l = rand.nextInt(255);
                int m = rand.nextInt(255);
                int n = rand.nextInt(255);
                int o = rand.nextInt(255);
Color color1 = new Color(a, b, c);
    Color color2 = new Color(d, e, f);
        Color color3 = new Color(g, h, i);
            Color color4 = new Color(j, k, l);
                Color color5 = new Color(m, n, o);
//Panel 1
JPanel Panel1 = new JPanel ();
Panel1.setBackground (color1);
Panel1.setPreferredSize (new Dimension (rand1));
JLabel label1 = new JLabel ("1");
Panel1.add(label1);
//Panel 2        
JPanel Panel2 = new JPanel ();
Panel2.setBackground (color2);
Panel2.setPreferredSize (new Dimension (rand2));
JLabel label2 = new JLabel ("2");
Panel2.add(label2);
Panel2.add(Panel1);

你可以引入一个方法

Random rand = new Random();
private Color randomColor() {
  return new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255));
}
public void yourMethod() {
  //Panel 1
  JPanel Panel1 = new JPanel ();
  Panel1.setBackground (randomColor());
  // ...
}

另一件要考虑的事情是使用一个数组来存储所有这些颜色。一种实现方法如下(使用Udo的randomColor()方法):

int[] myArray = new int[15];
for (int i = 0; i < 15; i++) {
    int[i] = randomColor();
}

同时,我认为你应该这样做:

rand.nextInt(256),因为nextInt(number)给你一个介于0(含)和数字(不含)之间的随机整数。因此,为了确保255是一个可能的值,您必须执行255 + 1 = 256。

最新更新