Display random images from folder to JLabel in Netbeans

淺唱寂寞╮ 提交于 2019-12-10 18:16:06

问题


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).


回答1:


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.


来源:https://stackoverflow.com/questions/21060810/display-random-images-from-folder-to-jlabel-in-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!