我創建了一個非常初學的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