为了账号安全,请及时绑定邮箱和手机立即绑定

加载FXML文件时出现“必填位置”异常

加载FXML文件时出现“必填位置”异常

DIEA 2019-10-21 15:15:10
我正在尝试加载FXML文件并将其显示为应用程序窗口,但出现异常。FXML文件是由FXML Scene Builder创建的。这是班级的代码public class Main extends Application {    public static void main(String[] args) {        launch(args);    }    @Override    public void start(Stage primaryStage) throws Exception {        primaryStage.setScene(FXMLLoader.load(getClass().getResource("sample.fxml")));        primaryStage.show();    }}和FXML文件<?xml version="1.0" encoding="UTF-8"?><?import javafx.scene.control.Button?><?import javafx.scene.control.TitledPane?><?import javafx.scene.layout.AnchorPane?><TitledPane animated="false" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity"            prefHeight="400.0" prefWidth="600.0" text="Pass4D" xmlns:fx="http://javafx.com/fxml/1"            xmlns="http://javafx.com/javafx/8">    <content>        <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="180.0" prefWidth="200.0">            <children>                <Button layoutX="211.0" layoutY="134.0" mnemonicParsing="false" prefHeight="33.0" prefWidth="177.0"                        text="Log in"/>                <Button layoutX="212.0" layoutY="170.0" mnemonicParsing="false" prefHeight="33.0" prefWidth="175.0"                        text="Exit"/>            </children>        </AnchorPane>    </content></TitledPane>这是我得到的例外Exception in Application start methodException in thread "main" java.lang.RuntimeException: Exception in Application start method    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:875)    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(LauncherImpl.java:157)    at com.sun.javafx.application.LauncherImpl$$Lambda$1/2074407503.run(Unknown Source)    at java.lang.Thread.run(Thread.java:745)Caused by: java.lang.NullPointerException: Location is required.    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3201)我究竟做错了什么?
查看完整描述

3 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

如果无法在运行时类路径(而不是当前目录等)上找到资源,则简短答案是静默getClass().getResource("sample.fxml")返回。null

因此,这取决于您的IDE项目设置,如果您使用的是eclipse,请尝试添加sample.fxml运行配置中的文件夹。

一些想法...

  • 尝试getClass().getResource("/sample.fxml")...

  • 尝试移至sample.fxml资源文件夹。我对您的IDE不太了解,但是我怀疑文件夹仅用于.java文件...对于eclipse中的gradle项目确实是这样-资源必须在src/main/resources树中,因为只有添加到运行时类路径中的资源。 ..


查看完整回答
反对 回复 2019-10-21
  • 3 回答
  • 0 关注
  • 1069 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信