如何在Swing中显示随机图像

Reu*_*ben 3 java collections swing

我想要一个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);

  } 
} 
Run Code Online (Sandbox Code Playgroud)

Sor*_*row 8

将文件名加载到ArrayList,构造java.util.Random并调用nextInt(arraylist.size())以获取随机数.然后在该数字的索引下显示位于数组中的文件.

或者,请更具体地说明您的问题.