JavaFx-java.lang.IllegalArgumentException:无效的URL或资源未找到

时间:2018-08-27 15:22:51

标签: javafx illegalargumentexception

我最近开始学习JavaFX,并且为我的班分配了以下作业:

编写一个在网格窗格中显示四个图像的程序。

这是我的代码:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class Ch_14_Ex_1 extends Application {
    @Override //Override the start method in the Application class
    public void start(Stage primaryStage) {
    //Create a pane to hold the image views
    GridPane pane = new GridPane();

    //Place nodes in the pane
    pane.add(new ImageView(new Image("image/ukFlag1.gif")), 0, 0);
    pane.add(new ImageView(new Image("image/canadaFlag1.gif")), 1, 0);
    pane.add(new ImageView(new Image("image/chineseFlag1.gif")), 0, 1);
    pane.add(new ImageView(new Image("image/usaFlag1.gif")), 1, 1);

    //Create a scene and place it in the stage
    Scene scene = new Scene(pane);
    primaryStage.setTitle("Ch_14_Ex_1"); //Set the stage title
    primaryStage.setScene(scene); //Place the scene in the stage
    primaryStage.show(); //Display the stage
  }
}

该程序可以正常编译,但是每当我尝试运行该程序时,都会出现以下错误,并且不确定如何解决该问题。

Exception in Application start method
Exception in thread "JavaFX BlueJ Helper" java.lang.RuntimeException: 
Exception in Application start method
at  com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917) 

at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:748)

Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found

at javafx.scene.image.Image.validateUrl(Image.java:1118)
at javafx.scene.image.Image.<init>(Image.java:620)
at Ch_14_Ex_1.start(Ch_14_Ex_1.java:16)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1110)
... 11 more

1 个答案:

答案 0 :(得分:-1)

您可以在项目中设置资源文件夹,以防要将其包装在jar文件中并像这样加载它们
new Image(getClass.getResourceAsStream("image/yourImage.gif"))
要么
如果这些图像不在您的资源中,则可以像这样加载它们
new Image("file:image/yourimage.gif")