Button event for the first form:
@FXML protected void show2Action() throws IOException { Stage stage = new Stage(); AnchorPane pane = FXMLLoader.load(getClass().getResource("javafxcontroller2.fxml")); Scene scene = new Scene(pane,300,400); stage.setScene(scene); stage.show(); }
The code is very simple. The fxml file of the second form:
<?xml version="1.0" encoding="UTF-8"?> <?import javafx.scene.control.Button?> <?import javafx.scene.control.Label?> <?import javafx.scene.layout.AnchorPane?> <?import javafx.scene.layout.ColumnConstraints?> <?import javafx.scene.layout.GridPane?> <?import javafx.scene.layout.RowConstraints?> <AnchorPane fx:id="containerid" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.172-ea" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.javafxminademo.Javafxcontroller2"> <children> <GridPane layoutX="149.0" layoutY="116.0"> <columnConstraints> <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" /> <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" /> </columnConstraints> <rowConstraints> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" /> </rowConstraints> <children> <Label id="lblinfo" fx:id="lblinfo" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="1" /> <Button fx:id="btnid" mnemonicParsing="false" text="Button" GridPane.rowIndex="2" /> </children> </GridPane> </children> </AnchorPane>
But the program always says that the null pointer of FXMLLoader.load is abnormal. It is obvious that getClass().getResource is incorrect. After careful inspection, it is found that the path of my first controller's class is different from that of the second controller's class. Therefore, the path of getResource should take the class path of the second controller relative to that of the first controller as a parameter, and change to:
AnchorPane pane = FXMLLoader.load(getClass().getResource("../javafxcontroller2.fxml"));
Then everything is normal.