Tim*_*ron 3 label javafx nullpointerexception
我目前正在编写的程序遇到以下问题,我在互联网上进行了搜索,但我找不到任何东西可以帮助我理解以下问题
因此,在另一个类中,我编写了一个方法,每当单击搜索按钮时都会执行此方法,该方法如下所示:
public void searchButton(){
try {
new SearchController().display();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
然后 SearchController 类看起来像这样(我在这里简化了它):
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();
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我为什么可以在初始化方法上写入文本(该方法在该borderPane = loader.load();行之后被调用......那么如果我尝试在该行之后的标签上写入,为什么它不起作用?)
先感谢您
创建FXML 根元素的属性FXMLLoader中指定的类的实例。然后,当属性与字段名称匹配时fx:controller,它将 FXML 文件中定义的元素注入到它创建的控制器实例中。fx:id然后它调用initialize()该实例上的方法。
您可以使用“手动”创建控制器的实例new SearchController()。这与 所创建的对象不同FXMLLoader。所以现在当您加载 fxml 文件时,您有两个不同的SearchController. 所以如果你打电话what.setText(...)从该display()方法调用,则不会在FXMLLoader. 因此,what尚未在您调用的实例中初始化what.setText(...),并且您会收到空指针异常。
自从initialize()是由FXMLLoader所创建的实例调用的,因此当您what.setText(...)从该initialize()方法调用时,您是在 所创建的实例上调用它FXMLLoader,因此该实例的 FXML 注入字段已被初始化。
有关此问题的更多信息在以下问题的答案中提供:
| 归档时间: |
|
| 查看次数: |
8962 次 |
| 最近记录: |