通过代码在ImageView中加载图像

时间:2014-01-19 09:56:42

标签: image imageview javafx

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

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

1 个答案:

答案 0 :(得分:5)

Image的构造函数需要URL而不是文件路径。因此,如果字符串中有“:”,那么到目前为止的所有内容都会被解释为协议(通常类似httpfileftp)。

您必须更改行

String img = file.toString();

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

这会在转换为字符串之前从文件中获取URL。我首先转换为URI,因为File.toURL已被弃用,这是建议的“解决方法”。

相关问题