How To Align Ok Button Of A Dialog Pane In Javafx?

Viewed 7545

I want to align i.e Position CENTER an OK button of a DialogPane. I have tried the below code but its not working.

Dialog dialog = new Dialog();
DialogPane dialogPane = dialog.getDialogPane();
dialogPane.setStyle("-fx-background-color: #fff;");

        // Set the button types.
ButtonType okButtonType = new ButtonType("Ok", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
dialog.getDialogPane().getButtonTypes().addAll(okButtonType, cancelButtonType);
dialogPane.lookupButton(cancelButtonType).setVisible(false);

        // Testing
Button okButton = (Button) dialog.getDialogPane().lookupButton(okButtonType);
okButton.setAlignment(Pos.CENTER);
        // End Testing

dialog.showAndWait();
5 Answers

I tried to center OK button in Alert and I am not sure if this is bug or feature (Java8) but it was possible to center single button by setting new one:

alert.getButtonTypes().set(0, new ButtonType("OK", ButtonBar.ButtonData.LEFT));

As long as there is only one button with ButtonData.LEFT, it is centered in the middle of button panel. Obviously this solution does not work for panel with multiple buttons, but it might help to position single OK button.

Add this method to your code and call it when you need to align the buttons in a Dialog or Alert:

    private void centerButtons(DialogPane dialogPane) {
      Region spacer = new Region();
      ButtonBar.setButtonData(spacer, ButtonBar.ButtonData.BIG_GAP);
      HBox.setHgrow(spacer, Priority.ALWAYS);
      dialogPane.applyCss();
      HBox hboxDialogPane = (HBox) dialogPane.lookup(".container");
      hboxDialogPane.getChildren().add(spacer);
   }

Call it in this way: centerButtons(dialog.getDialogPane);

Based on @ManuelSeiche's answer, here is how to compute exact distance to the center:

@FXML private Dialog<ButtonType> dialog;
@FXML private ButtonType btClose;

@FXML
private void initialize()
{
    dialog.setOnShown(event ->
    {
        Platform.runLater(() ->
        {
            Button btnClose = (Button) dialog.getDialogPane().lookupButton(btClose);
            HBox hBox = (HBox) btnClose.getParent();
            double translateAmount = hBox.getWidth() / 2.0 - btnClose.getWidth() / 2.0 - hBox.getPadding().getLeft();
            btnClose.translateXProperty().set(-translateAmount);
        });
    });
}
Related