首页 > 解决方案 > 线程“main”java.lang.reflect.InvocationTargetException JavaFX 中的异常(首先由显示图像和播放音频文件引起)

问题描述

在你们给我另一个链接之前,我已经研究了我的案例 2 天但没有运气:(

我的问题是如何声明 ImageView/AudioClip/MediaPlayer 而不会收到错误消息

首先,让我向您展示错误消息:

Exception in thread "main" java.lang.reflect.InvocationTargetException

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)

Caused by: java.lang.ExceptionInInitializerError
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    ... 5 more

Caused by: java.lang.IllegalStateException: Not on FX application thread; currentThread = main
    at javafx.graphics/com.sun.javafx.tk.Toolkit.checkFxUserThread(Toolkit.java:291)
    at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(QuantumToolkit.java:424)
    at javafx.graphics/javafx.stage.Stage.<init>(Stage.java:254)
    at javafx.graphics/javafx.stage.Stage.<init>(Stage.java:240)
    at YuanGeometryWar/Output.Main.<clinit>(Main.java:18)
    ... 11 more

我知道这个问题是由于 image 的声明引起的:

现在的代码行如何(给我错误):

URL background = this.getClass().getResource("resources/Image/MenuBackGround.jpg");
ImageView menuBack = new ImageView(new Image(background.toString()));

mainPane.getChildren().add(menuBack);

以前的情况(与此类似并且有效):

try(InputStream pathIntro = Files.newInputStream(Paths.get("resources/Image/ControlBack.png"))){
        intro = new ImageView(new Image(pathIntro));

        controlPane.getChildren().add(intro);
    }

我在让 audioClip 或 MediaPlayer 工作时也遇到了同样的问题。

我只想知道为什么这会导致我出现问题,以及实现此类目标的正确方法是什么?

资源文件夹不在src中,直接在项目文件夹下

标签: javafxresourcesinvocationtargetexception

解决方案


推荐阅读