如何在Java中选择随机图片? [英] How to select random pictures in Java?

查看:350
本文介绍了如何在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"));

其中maxmin是图像的编号.对于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屋!

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