2

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 Answers1

2

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));
ItachiUchiha
  • 36,135
  • 10
  • 122
  • 176
  • I used the constructor of ImageView to add image.But I get this error "Caused by: java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c at javafx.scene.image.Image.validateUrl(Image.java:1097) at javafx.scene.image.Image.(Image.java:598) at javafx.scene.image.ImageView.(ImageView.java:164) at fileshare_client.fx.pkg1.UploadappUI_1Controller.iconimagebuttonAction(UploadappUI_1Controller.java:355)" java:355 which is "imageview=new ImageView(iconimage.getAbsolutePath());" – Kumaranath Fernado Sep 03 '14 at 13:33
  • Its because you need to append the absolute path with `file:` – ItachiUchiha Sep 03 '14 at 14:03
  • this might be helpful :[Runtime error IllegalArgumentException when setting Image javafx] (http://stackoverflow.com/questions/25646263/runtime-error-illegalargumentexception-when-setting-image-javafx) – Kumaranath Fernado Sep 03 '14 at 14:06