Use a controller class, so you do not need to use a search. FXMLLoaderwill enter the fields into the controller for you. Injection is guaranteed before the method initialize()(if you have one) is called
public class ViewController {
@FXML
private Button exitBtn ;
@FXML
private Button openBtn ;
public void initialize() {
}
@FXML
private void handleButtonClick(ActionEvent event) {
if (event.getSource() == exitBtn) {
exitBtn.getScene().getWindow().hide();
} else if (event.getSource() == openBtn) {
}
}
}
FXML:
<SomePane xmlns="..." fx:controller="my.package.ViewController">
<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1" />
<Button fx:id="openBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Open" HBox.hgrow="NEVER" HBox.margin="$x1" />
</SomePane>
, FXML , (, , Application)
Parent root = FXMLLoader.load(getClass().getResource("path/to/fxml"));
Scene scene = new Scene(root);