Skip to content
Advertisement

Load random Image from a directory using javafx

How can I load a random image from a directory using javafx, (the files located in the directory have different names)

Currently I am using the following to load a specific file

String image = JavaFXApplication4.class.getResource("/Images/Blue-Wallpaper.jpg").toExternalForm();

Advertisement

Answer

Thanks to Patrick I came up with a short version:

images = new ArrayList<String>();
directory = new File("/");

File[] files = directory.listFiles();
for(File f : files) 
{images.add(f.getName());}   
System.out.println(images);
int countImages = images.size();
int imageNumber = (int) (Math.random() * countImages);
String image = images.get(imageNumber);
System.out.println(image);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement