java - 在 Netbeans 中显示文件夹中的随机图像到 JLabel

标签 java image swing random netbeans-7

我的项目包含一个名为 images 的文件夹,其中包含图像。我想在按下按钮时将图像随机显示到框架中的 JLabel 中。我试过下面的代码:

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);
 }

此代码仅显示图像 a1。但是我随机需要这些图像(一次一张图像)。

最佳答案

使用类似的东西

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

randomNumber 变量生成一个随机数。只要您所有的图像都具有相同的前缀和不同的数字后缀,就可以了。


如果都不同,则将每个字符串路径存储到一个String数组中,随机数作为索引

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

示例

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);
}

更新 OP 评论

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

然后通过 File API 将文件名加载到数据结构中。file.list() <-- 返回一个 String[]

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

只要所有文件都是文件而不是目录,这应该可以正常工作。


更新

正如下面评论中所讨论的那样,上面的答案可能在部署时不起作用。这是@AndrewThompson 对文件问题的修复建议

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.

关于java - 在 Netbeans 中显示文件夹中的随机图像到 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21060810/

相关文章:

html - 如何隐藏图像上的线性背景?

java - GridBagLayout 中组件的大小不正确

java - 垂直 Swing 调整一个 Pane 的大小以扩大其他 Pane 的收缩(修改后的BorderLayout)

java - 在 Java 1.7 中使用 Android Studio

java - 在jframe上动态切换图像

java - shutdownHooks RuntimePermission 的作用是什么?

java - 图像处理: averaging filter on a grayscale image

python - Pygame:外星人入侵船图像

java - 从隐藏的 jPanel 中删除右侧水平间隙

java - 如何覆盖调用另一个方法的运行方法