I'm trying to set an JFX ImageView image from a resource folder, but can't seem to get an appropriate URL/String filepath that won't throw an exception.
var x = getRandomImageFromPackage("pictures").toString();
var y = getClass().getClassLoader().getResource("pictures/mindwave/active/Super Saiyan.gif").toString();
this.iconImageView.setImage(new Image(x));
x
returns
/home/sarah/Desktop/Dropbox/School/Current/MAX MSP Utilities/MindWaveMobileDataServer/target/classes/pictures/0515e3b7cb30ac92ebfe729440870a5c.jpg
whereas y
returns something that looks like:
file:/home/sarah/Desktop/Dropbox/School/Current/MAX MSP Utilities/MindWaveMobileDataServer/target/classes/pictures/mindwave/active/Super Saiyan.gif
In theory either of these would be acceptable, however, only x will throw an exception if it is placed in the below setImage(String)
line.
Is there any way to get a list of images in the package so that I can select a random one and set the ImageView?
I know that there was a custom scanner option, but it appears rather dated (being over 11 years old and wasn't really supported at the time):
CodePudding user response:
There is no easy and reliable way to do that. Therefore I create and put an inventory file into my resources folder. So at runtime I can read that in and then have all the file names awailable that I need.
Here is a little test that shows how I create that file:
public class ListAppDefaultsInventory { @Test public void test() throws IOException { List<String> inventory = listFilteredFiles("src/main/resources/app-defaults", Integer.MAX_VALUE); assertFalse("Directory 'app-defaults' is empty.", inventory.isEmpty()); System.out.println("# src/main/resources/app-defaults-inventory.txt"); inventory.forEach(s -> System.out.println(s)); } public List<String> listFilteredFiles(String dir, int depth) throws IOException { try (Stream<Path> stream = Files.walk(Paths.get(dir), depth)) { return stream .filter(file -> !Files.isDirectory(file)) .filter(file -> !file.getFileName().toString().startsWith(".")) .map(Path::toString) .map(s -> s.replaceFirst("src/main/resources/app-defaults/", "")) .collect(Collectors.toList()); } } }
CodePudding user response:
Issues with your approach
You don't have a well-formed url
execution command
Set the VM arguments for your JavaFX SDK installation:
-p C:\dev\javafx-sdk-17.0.2\lib --add-modules javafx.controls