Reputation: 5736
I want a Swing application which will randomly pick some images from a folder and will show them.
I've tried some thing like this but the images are not rendering.
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);
}
}
Upvotes: 3
Views: 3315
Reputation: 57391
Got list of images for the folder. Use File class list() method to get all file names ((or listFiles() if you need files). Use Random to get next integer. Use Toolkit.getDefaultToolkit().createImage(imgFileName) to create image. Create a JFrame (or JWindow), create a JLabel with the image and add to the JFrame.
Upvotes: 3
Reputation: 7188
Load the file names into an ArrayList
, construct java.util.Random
and call nextInt(arraylist.size())
to get a random number. Then display a file located in the array under the index of that number.
Alternatively, please be a little more specific with your question.
Upvotes: 8