gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:38:16 24 4
gpt4 key购买 nike

我正在编写一些代码,在其中与 start 方法中的 FXML 元素进行交互(更改文本)。但是,我发现当我从 Controller 类调用该方法时,我收到 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);
}
}

Controller 类:

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>

最佳答案

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

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

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

关于java - 在 start 方法中与 FXML 元素交互时如何修复 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com