设置图像的JavaFX运行时错误抛出:IllegalArgumentException(Runtim

2019-10-20 21:01发布

我得到这个错误

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 

这是

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

这里是我的代码:

@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
    }
}

Answer 1:

运用

iconimage.getAbsolutePath()

给你的文件,其中的构造函数需要一个绝对路径file URL

尝试使用

iconimage.toURI().toString()

或附加file:绝对路径

"file:" + iconimage.getAbsolutePath()


Answer 2:

下面是代码,我使用的片段。

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);
      }


Answer 3:

此URL在的ImageView的构造函数提供

所以建议代码如下:

 @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);
        }
    }

}


文章来源: Runtime error IllegalArgumentException when setting Image javafx