Reputation: 5532
I am trying to load an image in JavaFX using it's Image
class.
Here is my code:
Image image = new Image(file.getAbsolutePath());
file
is just a file loading the image.
I get the following error:
java.lang.IllegalArgumentException: Invalid URL or resource not found
Here's the full code:
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("JPG","*.jpg"),
new FileChooser.ExtensionFilter("JPEG","*.jpeg")
);
fileChooser.setTitle("Choose file...");
fileChooser.setInitialDirectory(
new File(System.getProperty("user.home"))
);
File file = fileChooser.showOpenDialog(stageOfEvent);
if(file != null) {
Image image = new Image(file.getAbsolutePath());
imageView.setImage(image);
}
Upvotes: 1
Views: 1064
Reputation: 137074
In order to construct an Image
with a file located in the filesystem, you need to use the file:
protocol, like this:
Image image = new Image("file:" + file.getAbsolutePath());
Not specifying it tells JavaFX to look for the image in the classpath, rather than in the filesystem.
Quoting the Image Javadoc:
// The image is located in my.res package of the classpath Image image2 = new Image("my/res/flower.png", 100, 150, false, false); // The image is located in the current working directory Image image4 = new Image("file:flower.png", 0, 100, false, false);
This construct comes from the URL
syntax of Java.
As noted by @mipa in the comments, you can also use:
Image image = new Image(file.toURI().toURL().toExternalForm());
Upvotes: 2