oldvipera
oldvipera

Reputation: 315

Loading an image in ImageView through code

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

Upvotes: 2

Views: 2205

Answers (1)

fabian
fabian

Reputation: 82461

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".

Upvotes: 5

Related Questions