【发布时间】:2016-07-11 06:13:54
【问题描述】:
我目前正在编写的程序遇到以下问题,我在互联网上进行了搜索,但我真的找不到任何东西可以帮助我理解以下问题
所以在另一个类中,我编写了一个方法,每当单击搜索按钮时都会执行此方法,该方法如下所示:
public void searchButton(){
try {
new SearchController().display();
} catch (IOException e) {
e.printStackTrace();
}
}
然后 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();
}
}
有人可以告诉我为什么可以在初始化方法上写文本(该方法在borderPane = loader.load(); 行之后被调用......那么如果我尝试在之后写在标签上为什么它不起作用行?)
提前谢谢你
【问题讨论】:
-
顺便说一句,请注意,如果您最终加载 FXML 文件两次(并同时显示两者),您的
static字段将是一场灾难。你根本不需要这些,它们是等待发生的错误。您可以使用cancelButton.setOnAction(e -> cancelButton.getScene().getWindow().hide());关闭窗口(并去掉stage字段。如果您确实需要borderPane字段,请将其设为实例变量并从fxml 文件中注入(即删除static和只需将fx:id="borderPane"放在 fxml 的根元素上)。
标签: javafx nullpointerexception label