我的项目包含一个名为 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:
- 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 anURL
to it.- Read it back in at run-time.
关于java - 在 Netbeans 中显示文件夹中的随机图像到 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21060810/