基本上,我需要從fxml文件中檢索VBox,並使用scene.lookup。 但是,如果我搜索它,它只是崩潰與NullPointerException。如果我搜索VBox,scene.lookup()返回null
所以我試圖打印什麼scene.lookup()發現,它只是發現null(杜),但我不明白爲什麼。
這是我的主類:
public class Main extends Application {
@Override
public void start(Stage stage) throws Exception{
FXMLLoader loader = new FXMLLoader(getClass().getResource("MainWindow.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root, 600, 575);
Controller controller = new Controller();
controller.setScene(scene);
System.out.println(scene.lookup("#vBox"));
stage.setScene(scene);
stage.setTitle("Test");
stage.setResizable(false);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
這是我FXML文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:id="borderPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="575.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Controller">
<top>
<ToolBar prefHeight="40.0" prefWidth="200.0" BorderPane.alignment="CENTER">
<items>
<Button fx:id="addBtn" mnemonicParsing="false" onAction="#addEventHandler" prefHeight="30.0" prefWidth="75.0" text="Add" />
<Button fx:id="editBtn" mnemonicParsing="false" prefHeight="30.0" prefWidth="75.0" text="Edit..." />
<Button fx:id="delBtn" mnemonicParsing="false" prefHeight="30.0" prefWidth="75.0" text="Delete" />
</items>
</ToolBar>
</top>
<center>
<ScrollPane fx:id="scrollPane" prefHeight="515.0" prefWidth="600.0" BorderPane.alignment="CENTER">
<content>
<VBox fx:id="vBox" fillWidth="true" />
</content>
</ScrollPane>
</center>
</BorderPane>
您是否試過單步執行代碼?如果是這樣,它會崩潰在哪條線上? – StillLearnin
@StillLearnin你不需要單步執行代碼。您可以從堆棧跟蹤中讀取它。但是,OP指出'scene.lookup(「#vBox」)正在返回null。 –