我正在嘗試加載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
樹中,因為只有添加到運行時類路徑中的資源。 ..
添加回答
舉報
0/150
提交
取消