如何在 JavaFX 8 警报对话框中更改是/否按钮的文本

2022-09-01 13:49:36

我有这个代码片段:

Alert alert = 
        new Alert(AlertType.WARNING, 
            "The format for dates is year.month.day. " +
            "For example, today is " + todayToString() + ".",
             ButtonType.OK, 
             ButtonType.CANCEL);
alert.setTitle("Date format warning");
Optional<ButtonType> result = alert.showAndWait();

if (result.get() == ButtonType.OK) {
    formatGotIt = true;
}

上面,我请求两个标题为“是”和“否”的按钮。但是,我希望将它们都更改。


答案 1

您可以定义自己的按钮类型。在此示例中,按钮的文本为 和 :foobar

ButtonType foo = new ButtonType("foo", ButtonBar.ButtonData.OK_DONE);
ButtonType bar = new ButtonType("bar", ButtonBar.ButtonData.CANCEL_CLOSE);
Alert alert = new Alert(AlertType.WARNING,
        "The format for dates is year.month.day. "
        + "For example, today is " + todayToString() + ".",
        foo,
        bar);

alert.setTitle("Date format warning");
Optional<ButtonType> result = alert.showAndWait();

if (result.orElse(bar) == foo) {
    formatGotIt = true;
}

答案 2
((Button) dialog.getDialogPane().lookupButton(ButtonType.OK)).setText("Not OK Anymore");
((Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL)).setText("Not Cancel Anymore");

推荐