我有一个JavaFX BlueJ项目。以下是简单的目录结构
正如您所看到的,我在同一目录中有Gui.java
和map.png
个文件。以下是我的代码
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Dragon Castle");
Game game = new Game();
TextArea logArea = new TextArea();
VBox vbox = new VBox(10);
// Create maps
Canvas canvas = new Canvas(770, 630);
Image map = new Image("map.png"); // Here it is giving error
GraphicsContext gc = canvas.getGraphicsContext2D();
// Insert controls
VBox controlsVbox = new VBox(5);
controlsVbox.setAlignment(Pos.CENTER);
HBox buttonHboxR1 = new HBox(5);
buttonHboxR1.setAlignment(Pos.CENTER); .... Other code
错误:
Exception in Application start method
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$152(LauncherImpl.java:182)
at com.sun.javafx.application.LauncherImpl$$Lambda$7/22058848.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1099)
at javafx.scene.image.Image.<init>(Image.java:608)
at src.Gui.start(Gui.java:46)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$57/5668924.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$53/812813.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$55/19277439.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$54/26973244.run(Unknown Source)
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$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$43/21354624.run(Unknown Source)
... 1 more
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1091)
... 16 more
找不到图片。我在eclipse中尝试了相同的代码,它的工作原理。我还将map.png
放在资源文件夹中,但它仍无法在BlueJ中使用。
答案 0 :(得分:0)
URL支持的所有URL都可以传递给构造函数。如果 传递的字符串不是有效的URL,而是一个路径,而不是Image 在那种情况下在类路径上搜索。
因此,由于您传递了一个简单的路径,Image
构造函数将尝试解析相对于类路径的路径。查看堆栈跟踪,您的Gui
类似乎位于名为src
的包中(真的???),并且您的图像位于同一个包中。因此,图像的路径应为src/map.png
。
从与当前类相同的包中检索图像的更好方法是从类对象获取URL作为资源:
Image map = new Image(getClass().getResource("map.png").toExternalForm());