如何在Java中选择随机图片? [英] How to select random pictures in Java?
本文介绍了如何在Java中选择随机图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个将使用以下代码的程序:
I'm making a program that will use a that will use this code:
JLabel MyImage = new JLabel(new ImageIcon("image1.png"));
但是,我想显示一个随机图片,例如image2,image3,image4.我该怎么做:
But, I want to make a random picture appear, say image2,image3,image4. How do I make this by:
- 不使用
List
- 不使用
Collections.shuffle
- 使用任何方法或数组.
- Not using a
List
- Not using
Collections.shuffle
- using any method or an array.
推荐答案
尝试一下
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
JLabel MyImage = new JLabel(new ImageIcon("image"+randomNum+".png"));
其中max
和min
是图像的编号.对于4张图片,说
image1,image2,image3,image4 min=1
max=4
Where max
and min
are the the numbers of your images. For 4 images, say
image1,image2,image3,image4 min=1
max=4
这篇关于如何在Java中选择随机图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文