Runtime error IllegalArgumentException when setting Image javafx

谁说我不能喝 提交于 2019-12-11 09:19:30

问题


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.<init>(Image.java:598)
at javafx.scene.image.ImageView.<init>(ImageView.java:164)
at fileshare_client.fx.pkg1.UploadappUI_1Controller.iconimagebuttonAction(Uploadapp‌​UI_1Controller.java:355)" java:355 

which is

imageview=new ImageView(iconimage.getAbsolutePath());"

here's my code:

@FXML
private AnchorPane mainAnchorpane;
@FXML
private ImageView imageview;
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);
      **imageview=new ImageView(iconimage.getAbsolutePath());**// error
    }
}

回答1:


Using

iconimage.getAbsolutePath()

gives you the absolute path of the file, where as the constructor expects a file URL

Try using

iconimage.toURI().toString()

or append file: to the absolute path

"file:" + iconimage.getAbsolutePath()



回答2:


Here is the snippet of code I use.

File imageFile = new File("mountains001.jpg");
      System.out.println(imageFile.getAbsolutePath());
      if (imageFile.exists()) {
         ImageView imageView = new ImageView();
         Image image = new Image(imageFile.toURI().toString());
         imageView.setImage(image);
         root.getChildren().add(imageView);
      }



回答3:


here URL has to provided in the constructor of ImageView

so the suggested code would be:

 @FXML
public void iconimagebuttonAction(ActionEvent event) {
    FileChooser filechooser = new FileChooser();
    iconimage = filechooser.showOpenDialog(mainAnchorpane.getScene().getWindow());
    System.out.println(iconimage.getName());
    if (iconimage != null) {
        try {
            String iconimagepath = iconimage.getAbsolutePath();
            System.out.println(iconimagepath);
            imageview=new ImageView(iconimage.toURI().toURL().toExternalForm());

        } catch (MalformedURLException ex) {
            Logger.getLogger(UploadappUI_1Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}


来源:https://stackoverflow.com/questions/25646263/runtime-error-illegalargumentexception-when-setting-image-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!