JavaFX,标签空指针异常

JavaFX, Label null pointer exception

我正在编写的程序遇到以下问题,我在互联网上进行了搜索,但我找不到任何可以帮助我理解以下问题的东西

所以在另一个 class 中,我编写了一个方法,只要单击搜索按钮就会执行此方法,该方法如下所示:

public void searchButton(){
        try {
            new SearchController().display();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

然后 SearchController class 看起来像这样(我在这里简化了它):

public class SearchController {

    @FXML
    private Button cancelButton;

    @FXML
    private Label what;

    private static Stage stage;

    private static BorderPane borderPane;

    @FXML
    public void initialize(){
        what.setText("Testing"); // this woks
        cancelButton.setOnAction(e -> stage.close());
    }

    public void display() throws IOException {

        stage = new Stage();
        stage.setResizable(false);
        stage.setTitle("Product search");
        stage.initModality(Modality.APPLICATION_MODAL);
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(SearchController.class.getResource("Search.fxml"));
        borderPane = loader.load();
        Scene scene = new Scene(borderPane);
        stage.setScene(scene);
        //what.setText("Testing") and this doesn't work
        stage.showAndWait();

    }



}

谁能告诉我为什么可以在初始化方法上写文本(该方法在 borderPane = loader.load(); 行之后被调用...所以如果我尝试写在该行之后的标签?)

提前致谢

FXMLLoader 创建 FXML 根元素的 fx:controller 属性中指定的 class 的实例。然后,当 fx:id 属性与字段名称匹配时,它会将 FXML 文件中定义的元素注入 它创建的 控制器实例。然后它在该实例上调用 initialize() 方法。

您使用 new SearchController() 创建控制器实例 "by hand"。这与 FXMLLoader 创建的对象不同。所以现在当您加载 fxml 文件时,您有两个不同的 SearchController 实例。因此,如果您从 display() 方法调用 what.setText(...),则不会在 FXMLLoader 创建的控制器实例上调用它。因此,what 尚未在您调用 what.setText(...) 的实例中初始化,您会得到一个空指针异常。

由于 initialize()FXMLLoader 在它创建的实例上调用,当您从 initialize() 方法调用 what.setText(...) 时,您是在实例上调用它由 FXMLLoader 创建,因此该实例的 FXML 注入字段已初始化。