我创建了一个非常初学的Java程序,可创建随机颜色和随机大小的五个面板(每个面板都小于下一个面板)。生成五个随机颜色,而不会创建15个随机变量
问题:
虽然我的程序工作,我不得不键入一个新的变量一切。对于每种颜色(R,G,B)的五个面板,我必须创建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);
请看看['loops'](http://www.homeandlearn.co.uk/java/ java_for_loops.html) – indivisible
你是否在重复任何事情?什么语言结构帮助我们重复? –
至少这是很容易理解的缩进。 – BitNinja