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:
- Create a small helper class that creates a list of the images.
- Write that list to a
File
, one name per line.
- Include the file as a resource (the easiest place is where the images are).
- Use
getResource(String)
to gain an URL
to it.
- Read it back in at run-time.