javafxvbox

JAVAFX Stage : Default button selection and alignment with text padding


I am new to Javafx and trying to implement a Warning/Confirmation Dialog box for the User.

I am able to get the dialog box, but unable to align it as per requirement.

Below is how my dialog box looks currently: enter image description here

Now, I need to make two changes,

  1. I want to have buttons side by side, with yes first and no after that. But No should be selected by default. So that on closing No is sent as response.
  2. I want to have some space between the text and the buttons. Also is it possible to get text in two lines if the text size increases?

Below is my current code:

public static boolean display(String title, String message){
        Stage window = new Stage();
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle("Confirmation");
        window.setMinWidth(540);
        window.setMinHeight(250);
        Label label = new Label();
        label.setText(message);

        Button yesButton = new Button("Yes");
        Button noButton = new Button("no");

        yesButton.setOnAction(e->{
            answer = true;
            window.close();
        });

        noButton.setOnAction(e->{
            answer = false;
            window.close();
        });
        
        VBox layout = new VBox(10);
        layout.getChildren().addAll(label,noButton,yesButton);
        layout.setAlignment(Pos.CENTER);
        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();
        return answer;
    }

Please help. Thanks in advance.


Solution

  • I want to have buttons side by side, with yes first and no after that

    Put the buttons into a HBox

    No should be selected by default. So that on closing No is sent as response.

    See here for a similar question

    I want to have some space between the text and the buttons.

    Add some margin to the top of the HBox you will put your Buttons into

    HBox h = //...
    HBox.setMargin(h, new Insets(20, 0, 0, 0));
    

    Also is it possible to get text in two lines if the text size increases?

    label.setWrapText(true);