whileloop
whileloop

Reputation: 35

Image class cannot find file?

The code below throws and error when I put in an absolute path for "king.png", but when I use an online link for the same image, there is no error. I also tried "king.png" as the parameter since the file is stored in the same folder as the .java file. Could someone explain some of the reasons why I'm getting this error? Thanks.

I'm 100% sure that the absolute file path is correct, I copied it from right click -> copy file path.

Code:

Image pic = new Image("C:\\Users\\Jae\\IdeaProjects\\CSE114\\src\\ex15\\king.png");

Error:

"Exception in thread "main" java.lang.IllegalArgumentException: Invalid URL: unknown protocol: c
    at javafx.scene.image.Image.validateUrl(Image.java:1102)
    at javafx.scene.image.Image.<init>(Image.java:608)
    at ex15.fileTest.main(fileTest.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.net.MalformedURLException: unknown protocol: c
    at java.net.URL.<init>(URL.java:593)
    at java.net.URL.<init>(URL.java:483)
    at java.net.URL.<init>(URL.java:432)
    at javafx.scene.image.Image.validateUrl(Image.java:1096)
    ... 7 more"

Upvotes: 0

Views: 338

Answers (1)

suppose bellow example for showing an image on your Scene, as you can see you should add file: to the begging of image path

public class ImageTest extends Application
{
    public void start(Stage primaryStage)
    {
        VBox  vBox = new VBox();

        Image image = new Image("file:C:\\Users\\Elyas\\Desktop\\New folder (2)\\1.jpg");
        ImageView imageView = new ImageView(image);

        vBox.getChildren().addAll(imageView);

        Scene scene = new Scene(vBox,100,100);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args)
    {
        launch();
    }

}

Upvotes: 1

Related Questions