2014-06-22 81 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