I'm trying to learn JavaFX and making a user list that can display user image from a user tableview. Here's the code that I have:
@FXML private ImageView image;
@FXML
public void buttonSHow(ActionEvent actionEvent) throws MalformedURLException, FileNotFoundException {
CList =TAbleview.getSelectionModel().getSelectedItems();
System.out.println(CList.get(0).getPicture());
//URL url = new URL(CList.get(0).getPicture());
//FileInputStream input = new FileInputStream (CList.get(0).getPicture());
image.setImage(new Image(CList.get(0).getPicture()));
}
What I'm trying to do with this code is setting up the ImageView
image with an Image
using the absolute path stored in the user list. The fxml
has this:
<ImageView fx:id = "image"/>
When I tried to run it, it gives me the error with MalformedURLException: unknown protocol e
. I tried to just punch in the url manually into the fxml
to see if it loads manually,
<ImageView>
<image>
<Image url = "@E:\test.jpg"/>
</image>
</ImageView>
but it still gives me the same error.
If you are intending to set the image based on a file in the file system (e.g. one chosen by the user), you need to create a URL representing the file.
You should not try to construct this yourself, but should use the File.toURI()
method, which handles creating the protocol and resolving file paths that are not valid URLs (e.g. file names containing illegal URL characters, such as whitespace) correctly.
So you should do
File file = new File(CList.get(0).getPicture());
image.setImage(new Image(file.toURI().toString()));