Loading an image in ImageView through code

为君一笑 提交于 2020-01-10 05:29:21

问题


I have built my application using scenebuilder for javafx. I have a form where a person has to upload an image. I used this code

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

And I got this error photoChooser method is called A:\images\fb\status\asd.jpg Can't upload image java.lang.IllegalArgumentException: Invalid URL: unknown protocol: a


回答1:


The constructor of Image expects an URL and not a file path. Therefore if there is a ":" in the string, everything up to that point is interpreted as the protocol (normally something like http, file or ftp).

You have to change the line

String img = file.toString();

to

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

This gets the URL from the file before converting to string. I converted to URI first since File.toURL is deprecated and that's the suggested "workaround".



来源:https://stackoverflow.com/questions/21215299/loading-an-image-in-imageview-through-code

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