2014-01-19 54 views
1

我已经为javafx使用scenebuilder构建了我的应用程序。我有一个人必须上传图片的表格。我用这个代码通过代码在ImageView中加载图像

public void photoChooser(ActionEvent evt) { 
    System.out.println("photoChooser method is called"); 
    try{ 
     FileChooser fileChooser= new FileChooser(); 
     fileChooser.setTitle("Choose a file"); 
     File file = fileChooser.showOpenDialog(stagehere); 
     if(file != null){ 
      System.out.println(file); 
      String img = file.toString(); 
      //Image image = new ImageIcon(img);   

      try{ 

     // image= new Image(); 
      Image image = new Image(img); 

      } catch (Exception e) {System.out.println("Can't upload image " + e);} 


      //employeeImage.setImage(image); 
      try{ 
      // employeeImage.setImage(image); 
      } catch(Exception e){System.out.println("Can't set the image" + e);} 
      employeeImage.setFitWidth(150); 
      employeeImage.setFitHeight(150); 
     } 

而且我得到这个错误 photoChooser method is called A:\images\fb\status\asd.jpg Can't upload image java.lang.IllegalArgumentException: Invalid URL: unknown protocol: a

+0

请将fabian的评论标记为已接受的答案,因为它的工作原理正是您要求的。 – Galya

回答

4

Image构造函数需要一个URL,而不是文件路径。因此,如果字符串中存在“:”,那么直到该点的所有内容都被解释为协议(通常类似http,fileftp)。

你必须转换为字符串前行

String img = file.toString(); 

改变

String img = file.toURI().toURL().toString(); 

这从文件的URL。我首先转换为URI,因为File.toURL已弃用,这就是建议的“解决方法”。

+0

谢谢。这是我想要的。 – oldvipera