2

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
  • Please mark the comment of fabian as an accepted answer, because it's working and it's what you have asked for. Commented Nov 10, 2015 at 20:56

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.