我想要一个 Swing 应用程序,它会从文件夹中随机选择一些图像并显示它们。
我试过类似的方法,但图像没有渲染。
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class RandomCards extends JFrame
{
RandomCards()
{
setLayout(new FlowLayout(FlowLayout.LEFT, 25, 10));
Map<Integer, String> hm = new HashMap<Integer, String>();
int noOfImage=3;
for(int i=0; i < noOfImage; i++)
{
hm.put(i, "resources/" + i + ".png");
}
double cardNumber = Math.floor(Math.random()*3) + 1;
add(new JLabel(hm.get(cardNumber)));
}
public static void main (String [] args)
{
RandomCards frame = new RandomCards();
frame.setSize(330, 150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
最佳答案
将文件名加载到ArrayList
中,构造java.util.Random
并调用nextInt(arraylist.size())
得到一个随机数。然后显示位于该数字索引下的数组中的文件。
或者,请将您的问题更具体一些。
关于java - 如何在 Swing 中显示随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6185130/