3

My project contains a folder named images containing images. I want to display the images randomly to the JLabel in the frame when a button pressed. I tried the code below:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
 {
    Image im=new ImageIcon(this.getClass().getResource("/images/a1.jpg")).getImage();
    ImageIcon iconLogo = new ImageIcon(im);
    jLabel2.setIcon(iconLogo);
 }

This code displays only the image a1. But I need the images randomly (one image at a time).

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
spc
  • 131
  • 5
  • 19
  • Check [`ImageViewer`](http://stackoverflow.com/a/13463684/418556) for tips on displaying multiple images. 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve). 2) One way to get image(s) for an example is to hot-link to the images seen in [this answer](http://stackoverflow.com/a/19209651/418556) (another way is shown in the `ImageViewer` code). – Andrew Thompson Jan 11 '14 at 09:53

1 Answers1

5

Use something like

..getResource("/images/a" + randomNumber + ".jpg")

Genderate a random number for randomNumber variable. As long as all your images have the same prefix and just different numerical suffix, you should be fine.


If they're all different, then store each string path into a String array and the random number will be the index

getResource("/images/" + pathArray[randomNumber])

Example

String[] imageNames {"hello.jpg", "world.png", "!.gif"};
Random rand = rand = new Random();
....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
    int index = rand.nextInt(3);

    Image im=new ImageIcon(this.getClass()
                .getResource("/images/" + imageNames[index])).getImage();
    ImageIcon iconLogo = new ImageIcon(im);
    jLabel2.setIcon(iconLogo);
}

UPDATE to OP comment

"Oh!if the folder contains 100 pictures it seems very difficult.My project needs more images"

then load the filed names into a data structure via the File API.. file.list() <-- return a String[]

File file = new File("src/images");
String[] imageNames = file.list(); 
...
int index = rand.nextInt(imagNames.length);

As long as all the files are files and not directories, this should work fine.


UPDATE

As discussed below in the comments, its been noted that the above answer will probably not work at time of deployment. Here is @AndrewThompson's suggestion as a fix to the file problem

The best way I can think of is:

  1. Create a small helper class that creates a list of the images.
  2. Write that list to a File, one name per line.
  3. Include the file as a resource (the easiest place is where the images are).
  4. Use getResource(String) to gain an URL to it.
  5. Read it back in at run-time.
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720