2014-06-22 80 views
0

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

請看看['loops'](http://www.homeandlearn.co.uk/java/ java_for_loops.html) – indivisible

+2

你是否在重複任何事情?什麼語言結構幫助我們重複? –

+0

至少這是很容易理解的縮進。 – BitNinja

回答

4

您可以介紹的方法

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()); 
    // ... 
} 
+0

關於格式化的一些注意事項:1.不要大寫'Panel1'。 2.縮進四個空格。 3.不要在方法名稱和參數之間放置空格。 –

+0

你是對的,從原始代碼複製粘貼了兩行。 –

+0

謝謝你。他們沒有告訴我們任何這樣的事情,所以我很驚訝他們期望我們用多個窗格來做這樣的問題。 – user2876630

-1

另一個要考慮的是使用數組存儲所有這些顏色。一個實現將是如下(使用烏的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.

+0

謝謝,我忘了範圍從0開始。 – user2876630