在Netbeans中显示从文件夹到JLabel的随机图像 [英] Display random images from folder to JLabel in Netbeans

查看:58
本文介绍了在Netbeans中显示从文件夹到JLabel的随机图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

此代码仅显示图像a1.但是我需要随机的图像(一次只需要一张图像).

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

推荐答案

使用类似

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

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

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.

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

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

示例

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

哦!如果文件夹中包含100张图片,这似乎非常困难.我的项目需要更多图片"

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

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.

更新

如下面的注释中所述,已注意到上面的答案可能在部署时不起作用.这是@AndrewThompson的建议,可以解决文件问题

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. 创建一个小的帮助程序类,以创建图像列表.
  2. 将该列表写为File,每行一个名称.
  3. 将文件包含为资源(最简单的位置是图像所在的位置).
  4. 使用getResource(String)为其获取URL.
  5. 在运行时读回它.
  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.

这篇关于在Netbeans中显示从文件夹到JLabel的随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆