So, I design 12 labels and 1 button, and I have a folder contains 12 images; my question is how can I make auto images shuffle from the folder to the 12 labels each time I press the button?? everything working good but the problem the images did not shuffle. I will be so thankful for any help
the code I use is:
File file = new File("src/Images"); String[] imageNames = file.list(); private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { Image im1=new ImageIcon(this.getClass().getResource("/Images/img1.png")).getImage(); ImageIcon iconLogo1 = new ImageIcon(im1); Image im2=new ImageIcon(this.getClass().getResource("/Images/img2.png")).getImage(); ImageIcon iconLogo2 = new ImageIcon(im2); Image im3=new ImageIcon(this.getClass().getResource("/Images/img3.png")).getImage(); ImageIcon iconLogo3 = new ImageIcon(im3); jLabel1.setIcon(iconLogo1); jLabel2.setIcon(iconLogo2); jLabel3.setIcon(iconLogo3); ArrayList <ImageIcon> list= new ArrayList<>(); list.add(iconLogo3); list.add(iconLogo2); list.add(iconLogo1); Collections.shuffle(list); }
Advertisement
Answer
What do you expect to see:
jLabel1.setIcon(iconLogo1); jLabel2.setIcon(iconLogo2); jLabel3.setIcon(iconLogo3); ArrayList <ImageIcon> list= new ArrayList<>(); list.add(iconLogo3); list.add(iconLogo2); list.add(iconLogo1); Collections.shuffle(list);
- First you add the Icons to each JLabel
- Then you add the Icons to an ArrayList
- Then your shuffle the ArrayList
Shuffling the ArrayList has nothing to do with the Icon added to the JLabel, so of course the Icons will always appear in the same order.
If you want the Icons on the labels to be shuffled, then you need to add the Icon to the label AFTER you shuffle the ArrayList.
Something like:
Collections.shuffle(list); jLabel1.setIcon(list.get(0)); jLabel2.setIcon(list.get(1)); jLabel3.setIcon(list.get(2));
Of course if you have 12 labels you would not want to write the code manually. You should also add your 12 labels to an Array (or ArrayList) and then write a loop to set the Icon of each label in the Array.