I am having the following problem with a program that I am currently writing, and I have searched on the internet, but I couldn't really find anything to help me understand the following problem
So inside another class I have written a method that executes this whenever the search button is clicked and the method looks like this:
public void searchButton(){
try {
new SearchController().display();
} catch (IOException e) {
e.printStackTrace();
}
}
And then the SearchController class looks something like this (I simplified it here):
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();
}
}
Can someone please tell me why it is possible to write text on the initialize method (that method gets called after the borderPane = loader.load(); line...so why doesn't it work if I try to write on the label after that line?)
Thank you in advance
staticfields are going to be a disaster if you ever end up loading the FXML file twice (and having both displayed at the same time). You don't need these at all, and they are bugs waiting to happen. You can usecancelButton.setOnAction(e -> cancelButton.getScene().getWindow().hide());to close the window (and get rid of thestagefield. If you really need theborderPanefield, make it an instance variable and inject it from the fxml file (i.e. removestaticand just putfx:id="borderPane"on the root element of the fxml).