JavaFX 和 maven:NullPointerException:需要位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22000423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:56:57  来源:igfitidea点击:

JavaFX and maven: NullPointerException: Location is required

javamavenjavafx

提问by OxySocks

I have been trying to get Maven set up with JavaFX. Even though I was unexperienced with Maven and JavaFX, I didn't expect it to be so much of a challenge. My Java knowledge is pretty solid (including Swing), and didn't expect to have this much difficulty getting it set up.

我一直在尝试使用 JavaFX 设置 Maven。尽管我对 Maven 和 JavaFX 没有经验,但我没想到它会带来如此大的挑战。我的 Java 知识非常扎实(包括 Swing),没想到设置起来会这么困难。

I started with a JavaFX project supplied by IntelliJ 13.0 Community Edition. The code in my Main class is relatively small:

我从 IntelliJ 13.0 Community Edition 提供的 JavaFX 项目开始。我的Main类中的代码比较少:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application
{
    @Override
    public void start(Stage primaryStage) throws Exception
    {
        //getClass().getResource("../../resources/sample.fxml");
        Parent root = FXMLLoader.load(getClass().getResource("../sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


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

and my pom.xmlisn't too big either:

pom.xml的也不太大:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>sample</groupId>
    <artifactId>JavaFXDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <organization>
        <name>RubberDucky</name>
    </organization>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>com.zenjava</groupId>
                    <artifactId>javafx-maven-plugin</artifactId>
                    <version>2.0</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>com.zenjava</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>2.0</version>
                <configuration>
                    <mainClass>sample.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>javafx</artifactId>
            <version>2.2</version>
            <systemPath>${java.home}/lib/jfxrt.jar</systemPath>
            <scope>system</scope>
        </dependency>
    </dependencies>
</project>

I'm using the JavaFX Maven Pluginto build the application. After running mvn clean jfx:jareverything seems fine, all builds succeed. But when I try to run the application I get the following error:

我正在使用JavaFX Maven 插件来构建应用程序。运行mvn clean jfx:jar一切正常后,所有构建都成功了。但是当我尝试运行该应用程序时,出现以下错误:

Exception in Application start method
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at com.javafx.main.Main.launchApp(Main.java:698)
        at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
        at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown So
urce)
        at com.sun.javafx.application.LauncherImpl.access
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("sample.fxml"));
0(Unknown Source) at com.sun.javafx.application.LauncherImpl.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.NullPointerException: Location is required. at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at javafx.fxml.FXMLLoader.load(Unknown Source) at sample.Main.start(Main.java:15) at com.sun.javafx.application.LauncherImpl.run(Unknown Source) at com.sun.javafx.application.PlatformImpl.run(Unknown Source) at com.sun.javafx.application.PlatformImpl.run(Unknown Source) at com.sun.javafx.application.PlatformImpl.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.run(Unknown Source) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.access0(Unknown Source) at com.sun.glass.ui.win.WinApplication.run(Unknown Source) ... 1 more

After some rough debugging the trouble seems to be in the path I am loading my files from. After hardcoding the sample.fxmlto a place on my hard drive, the application runs without any problems. Same goes for the current setup (seen above) when running the application from IntelliJ.

经过一些粗略的调试后,问题似乎出在我加载文件的路径上。将 硬编码sample.fxml到我的硬盘驱动器上的某个位置后,应用程序运行没有任何问题。从 IntelliJ 运行应用程序时,当前设置(如上所示)也是如此。

I feel like I have exhausted every resource (including StackOverflow, some very similar errors) but I just can't figure out what exactly is wrong.

我觉得我已经用尽了所有资源(包括 StackOverflow,一些非常相似的错误),但我无法弄清楚到底是哪里出了问题。

采纳答案by Absurd-Mind

Make sure that your sample.fxmlis in the src/main/resources/directory (or a subdirectory). Then you can access the file like this:

确保您sample.fxmlsrc/main/resources/目录(或子目录)中。然后你可以像这样访问文件:

Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));

Explanation: During the compile phase all resources and classes get copied to target/classes/. So your fxml file resides in this directory and your class in a subdirectory regarding its package name. If you call getClass().getResource("sample.fxml");the file will be searched relative to the class file which will be this directory: target/classes/sample/.

说明:在编译阶段,所有资源和类都被复制到target/classes/. 因此,您的 fxml 文件位于此目录中,而您的类位于关于其包名称的子目录中。如果您调用getClass().getResource("sample.fxml");该文件,则将搜索相对于该目录的类文件:target/classes/sample/.

Calling .getResource()on the classloader sets the relative search path to target/classes/and therefore your file gets found.

调用.getResource()类加载器会将相对搜索路径设置为target/classes/,从而找到您的文件。

P.S. You could also write:

PS你也可以写:

FXMLLoader loader = new FXMLLoader(getClass().getResource("TechJFX.fxml"));

回答by Techidiot

For me I had took care of following things -

对我来说,我已经处理了以下事情-

  1. Make sure fxml file is placed where your main class resides. And then load it using this - (In my case, TechJFX.fxml is the file)

    FXMLLoader loader = new FXMLLoader(getClass().getResource("TechJFX.fxml"));
    
  2. Add opencv-*.jar to your project folder (In my case opencv-300.jar)

  3. Add the jar to the build path using

  1. 确保 fxml 文件放置在您的主类所在的位置。然后使用它加载它 - (在我的情况下,TechJFX.fxml 是文件)

     static{ 
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
       }
    
  2. 将 opencv-*.jar 添加到您的项目文件夹(在我的情况下为 opencv-300.jar)

  3. 使用以下命令将 jar 添加到构建路径

Right click on the project folder -> Build Path -> Configure Build Path -> Libraries Tab -> Add External JARS and locate the jar

右键单击项目文件夹 -> Build Path -> Configure Build Path -> Libraries Tab -> Add External JARS 并找到 jar

Also, under Order and Export -> Tick opencv-300.jar and JRE System Library(if not already ticked)

另外,在 Order and Export -> 勾选 opencv-300.jar 和 JRE System Library(如果还没有勾选)

  1. Copy opencv_java*.dll (In my case opencv_java300.dll) to the same location where you jar is in the project folder.

  2. Add the following method to your main class

     static{ 
            System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
       }
    
  3. Done.

  1. 将 opencv_java*.dll(在我的例子中为 opencv_java300.dll)复制到 jar 在项目文件夹中的相同位置。

  2. 将以下方法添加到您的主类

    <build>
        ...
        <resources>
            <resource>
                <filtering>false</filtering>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.fxml</include>
                </includes>             
            </resource>
        </resources>
        ...
    </build>
    
  3. 完毕。

Hope this helps someone facing similar issue.

希望这可以帮助面临类似问题的人。

回答by mrak

As @Absurd-Mind already explained, maven will not copy any resource files (like fxml) which resides under the srcdirectory.

正如@Absurd-Mind 已经解释过的那样,maven 不会复制驻留在src目录下的任何资源文件(如 fxml)。

If you want to keep the fxmlfiles besides the java source files, you can use the maven resource plugin to copy them:

如果你想保留fxmljava源文件之外的文件,你可以使用maven资源插件来复制它们:

sourceSets.main.resources {
    srcDirs = ["src/main/java"]; //assume that your java classes are inside this path
    exclude "**/*.java"
}

回答by Saeed Masoumi

For those who use gradleas their build system add this to your build.gradlefile:

对于使用gradle作为构建系统的人,请将其添加到您的build.gradle文件中:

##代码##

Then clean and rebuild your project.

然后清理并重建您的项目。

So what will it do? If you have a view.fxmlinside your com.example.myfxapppackage, after building your project it will exported to <build dir>/resources/com/example/myfxapp/view.fxml

那么它会做什么呢?如果您view.fxmlcom.example.myfxapp包中有一个,在构建项目后,它将导出到<build dir>/resources/com/example/myfxapp/view.fxml

回答by Kamil Nekanowicz

I had the same issue with Intelij and Gradle.

我在 Intelij 和 Gradle 上遇到了同样的问题。

Steps to fix:

修复步骤:

1.Move file

1.移动文件

sample.fxml

示例文件

to path

到路径

\src\main\resources\fxml

\src\main\resources\fxml

  1. Set path on this file:
  1. 在此文件上设置路径:

Parent root = FXMLLoader.load(getClass().getResource("/fxml/sample.fxml"));

父根 = FXMLLoader.load(getClass().getResource("/fxml/sample.fxml"));

回答by ybdesire

my case is installed the javafx sdk to C:\Program Files\Java\openjfx-11.0.2_windows-x64_bin-sdk.

我的情况是将 javafx sdk 安装到C:\Program Files\Java\openjfx-11.0.2_windows-x64_bin-sdk.

And root cause is the the space contained in the sdk path name.

根本原因是 sdk 路径名中包含的空间。

Fixed by install the javafx sdk to folder which name without space, such as C:\javafx-sdk-11.0.2\lib

通过将javafx sdk安装到名称没有空格的文件夹来修复,例如 C:\javafx-sdk-11.0.2\lib