Reputation: 9
I'm creating a very beginner Java program that creates five Panels of random color and random size (each panel smaller than the next).
The problem:
While my program works, I've had to type a new variable for everything. For the five panels with 3 colors each (R,G,B) I've had to create 15 variables. Isn't there a way to call upon random within the (R,G,B) rather than creating so many variables?
Here is an excerpt of my code that deals with how the color is randomized in each panel:
//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);
Upvotes: 0
Views: 298
Reputation: 9345
Another thing to consider is using an array to store all of these colors. One implementation would be as follows (using Udo's randomColor() method):
int[] myArray = new int[15];
for (int i = 0; i < 15; i++) {
int[i] = randomColor();
}
Also, I think you want to do:
rand.nextInt(256)
, since nextInt(number)
gives you a random integer between 0 (inclusive) and number (exclusive). So to make sure 255 is a possible value, you'd have to do 255 + 1 = 256.
Upvotes: -1
Reputation: 5315
You can introduce a method
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());
// ...
}
Upvotes: 4