how to set file(image) on imageview


Question

I want to set an image on an imageview,selecting file from filechooser I used imageView.setImage(file), which prompts an error saying "File cannot be converted to Image"

here's my code:

@FXML
private AnchorPane mainAnchorpane;
@FXML
private ImageView iconimageview;
private File iconimage;

 @FXML
public void iconimagebuttonAction(ActionEvent event) {
    FileChooser filechooser = new FileChooser();
    iconimage = filechooser.showOpenDialog(mainAnchorpane.getScene().getWindow());
    System.out.println(iconimage.getName());
    if (iconimage != null) {
        String iconimagepath = iconimage.getAbsolutePath();
        System.out.println(iconimagepath);
        iconimageview.setImage(iconimage);
    }

}
1
1
9/3/2014 11:25:22 AM

Accepted Answer

You cannot set an path directly to setImage(). There exists no method for ImageView which accepts a file-path as parameter.

Though you can achieve the same using the constructor of ImageView which accepts a URL as a parameter

ImageView imageView = new ImageView(filepath)

or, creating a Image object using the filepath and then assigning it to the ImageView

imageView.setImage(new Image(filepath));
1
9/3/2014 12:55:27 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon