JAVAFX Stage:默认按钮选择和文本填充对齐

JAVAFX Stage : Default button selection and alignment with text padding

我是 Javafx 的新手,正在尝试为用户实现一个 Warning/Confirmation 对话框。

我能得到对话框,但无法按要求对齐。

下面是我的对话框当前的样子:

现在,我需要做两个改变,

  1. 我想要并排放置按钮,首先是,然后是否。但默认情况下应选择否。以便在关闭时发送 No 作为响应。
  2. 我想在文本和按钮之间添加一些 space。如果文本大小增加,是否也可以在两行中获取文本?

下面是我当前的代码:

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;
    }

请帮忙。提前致谢。

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

将按钮放入 HBox

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

有关类似问题,请参阅 here

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

在要将按钮放入的 HBox 顶部添加一些边距

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);

Buttonclass不支持.setSelected方法,所以我们只好使用ToggleButtonclass:

    ToggleButton yesToggleButton = new ToggleButton("Yes");

    ToggleButton noToggleButton = new ToggleButton("No");

    noToggleButton.setSelected(true);

你也可以看到,Toggle这个词出现在ToggleButtonclass中,意思是这个按钮可以被选中,也可以不被选中。


现在我们必须将 class ToggleButtonobjects 分配给一个 ToggleGroup 对象,因为 class 的 objects ] ToggleButton 可由 class ToggleGroup:

管理
ToggleGroup toggleGroup = new ToggleGroup();

yesToggleButton.setToggleGroup(toggleGroup);

noToggleButton.setToggleGroup(toggleGroup);

要创建与按钮的距离,我们现在必须指定 abscissa axisordinate axis 的坐标:

    yesToggleButton.setTranslateX(-100); // abscissa axis
    yesToggleButton.setTranslateY(25);  // ordinate axis

    noToggleButton.setTranslateX(100); // abscissa axis
    noToggleButton.setTranslateY(25); // ordinate axis

如果字体变大,字体不再可读,可以使用.setWrapText方法换行显示:

messageType.setFont(Font.font(20)); // sets the font size

messageType.setWrapText(true);

您使用了 VBox class,它使 objects 垂直对齐。既然你想让objects水平,你可以用HBox,或者让objects任意方向对齐,我推荐StackPane:

StackPane root = new StackPane();

我会向您推荐这种布景方法:

Stage confirmationWindow = new Stage();

confirmationWindow.setScene(new Scene(root, 540, 323));