How to show random image in Swing

I want Swing to arbitrarily select some images from a folder and display them.

I tried something like this, but images are not displayed.

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);

  } 
} 
+3
source share
2 answers

Got a list of images for the folder. Use the class list () method to get all the file names ((or listFiles () if you need the files). Use Random to get the next integer. Use Toolkit.getDefaultToolkit () to create the image. CreateImage (imgFileName). Create a JFrame (or JWindow), create a JLabel with an image and add it to the JFrame.

+3
source

ArrayList, java.util.Random nextInt(arraylist.size()), . , .

, , .

+8

All Articles