如何在start方法中与FXML元素交互时修复NullPointerException?

时间:2016-05-11 13:55:26

标签: java javafx fxml

我正在编写一些代码,用于与start方法中的FXML元素进行交互(更改文本)。但是,我发现当我从我的控制器类调用该方法时,我得到一个NullPointerException。我发现这个问题与线程有关,但我已经能够得到任何工作。我已经包含了一些产生相同问题的示例代码。

主要课程:

public class Main extends Application {
    Controller C = new Controller();

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        Scene scene = new Scene(root, 300, 275);
        stage.setTitle("FXML Welcome");
        stage.setScene(scene);
        stage.show();
        C.handleSubmitButtonAction();//Error happens here.
    }

    public static void main(String[] args) {
        launch(args);
    }
}

控制器类:

public class Controller{
    @FXML public Text actiontarget;

    @FXML protected void handleSubmitButtonAction() {
        actiontarget.setText("Sign in button pressed");
    }
}

FXML代码:

<GridPane fx:id="GridPane" fx:controller="sample.Controller" xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
    <children>
        <Text text="Welcome" GridPane.columnIndex="0" GridPane.rowIndex="0" GridPane.columnSpan="2"/>
        <Label text="User Name:" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
        <TextField GridPane.columnIndex="1" GridPane.rowIndex="1"/>
        <Label text="Password:" GridPane.columnIndex="0" GridPane.rowIndex="2"/>
        <PasswordField fx:id="passwordField" GridPane.columnIndex="1" GridPane.rowIndex="2"/>
        <HBox spacing="10" alignment="bottom_right" GridPane.columnIndex="1" GridPane.rowIndex="4">
            <Button text="Sign In" onAction="#handleSubmitButtonAction"/>
        </HBox>
        <Text fx:id="actiontarget" GridPane.columnIndex="1" GridPane.rowIndex="6"/>
    </children>
</GridPane>

1 个答案:

答案 0 :(得分:2)

FXMLLoader如果使用fxml中的fx:controller属性指定控制器类,则会创建控制器本身的实例。

要访问该实例,您需要创建FXMLLoader 实例,并在加载fxml后使用getController()。否则,注入值的控制器实例与您自己创建的实例不同,并存储在C字段中:

FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"))
Parent root = loader.load();
C = loader.getController();