Dokimi
Dokimi

Reputation: 27

How I can add(label) random in JFrame?

I try to make the memoryCard Game...

Is there a way to add(labels) in a JFrame window RANDOM?

I use FlowLayout and I have:

add(l1);add(l2);add(l3);add(l4); 

If I write somthing like this:

add(l3);add(l4);add(l1);add(l2);

changing series of images.. That's what I want... to add the labels with different position every time..

If not, is there a way to put with different row (random) the images in labels? I have this way to put the images:

imageOfLabel1 = imageOfLabel2 = "im1.jpg"; 
imageOfLabel3 = imageOfLabel4 = "im2.jpg"; 

Sorry about my English! : )

Upvotes: 0

Views: 162

Answers (1)

nidu
nidu

Reputation: 559

I'm not sure what's the type of l1, l2, l3 and l4. Suppose they all are JLabel instances. Then you can create an array, shuffle it and then add:

JLabel[] ls = new JLabel[] {l1, l2, l3, l4};

// shuffle
Random rand = new Random();
for (int i = 0; i < ls.length; i++) {
    int randIndex = rand.nextInt(ls.length);
    JLabel temp = ls[i];
    ls[i] = ls[randIndex];
    ls[randIndex] = temp;
}

for (int i = 0; i < ls.length; i++) add(ls[i]);

Upvotes: 1

Related Questions