java.lang.NullPointerException:位置仍然不起作用

时间:2018-01-08 22:23:21

标签: javafx fxml fxmlloader

我还遇到了一些试图让我的JavaFX程序运行的问题。像其他一些人一样,我不断收到错误package application; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.stage.Stage; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; public class Main extends Application { @Override public void start(Stage primaryStage) { try { Parent root = FXMLLoader.load(getClass().getResource("application/Main.fxml")); Scene scene = new Scene(root, 400, 400); scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { launch(args); } } fxml文件在Application包中。我已经尝试过我在这里找到的所有补救措施,但也许我错过了什么?这是我的代码

java.lang.NullPointerException: Location is required.
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3207)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
    at application.Main.start(Main.java:18)
    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)

这是错误


warning: squelched 1 whitespace error
warning: 6 lines add whitespace errors.

非常感谢任何帮助。提前致谢

3 个答案:

答案 0 :(得分:0)

我在Netbeans中与这个问题争吵了一整天。这就是我解决它的方法:首先,我将fxml文件放在与main相同的包中(尽管它甚至可以在单独的包中工作)。其次,我使用getClassLoader()指定文件的路径。这是代码:`   公共课主要{

public static void main(String[] args) {
    System.out.println("Test  = "+Main.class.getClassLoader().getResource("FXMLDocument.fxml"));`

运行项目之后,这是输出:.... NetBeansProjects / JavaFXApplicationTest / dist / JavaFXApplicationTest.jar!/FXMLDocument.fxml 请注意,单独运行文件之前会生成错误。

答案 1 :(得分:0)

这将起作用:

"/application/Main.fxml"

您只需要添加/

答案 2 :(得分:-3)

通过在src文件夹中拖放Main.fxml来解决问题。如果在其他地方找到此解决方案,请删除此帖子。