2014-09-03 77 views
0

,當我得到這個錯誤運行時錯誤拋出:IllegalArgumentException設置圖片的JavaFX

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

回答

2

使用

iconimage.getAbsolutePath() 

給你的文件,其中的構造函數需要一個file URL

嘗試使用絕對路徑

iconimage.toURI().toString() 

或追加file:到絕對路徑

"file:" + iconimage.getAbsolutePath() 
0

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

} 
1

這是我使用的代碼片段。

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); 
     } 
相關問題