JavaFX (8) 警报 : different button sizes

标签 javafx dialog javafx-8

考虑一个带有两个按钮的 JavaFX (8) 警报对话框:

Alert alert = new Alert(AlertType.CONFIRMATION);

ButtonType bttYes = new ButtonType("Yes");
ButtonType bttNo = new ButtonType("No, continue without restart");

alert.getButtonTypes().clear();
alert.getButtonTypes().addAll(bttYes, bttNo);

alert.showAndWait();

生成的对话框有两个按钮,宽度相同,看起来很傻。

有没有办法将两个按钮调整为实际文本长度?

最佳答案

Alert 扩展了 Dialog,包装了 DialogPaneDialogPane 分为不同的部分,其中一个部分是“按钮栏”。正如预期的那样,此部分是所有按钮所在的位置。按钮栏可以是任意 Node,但 DialogPane 的默认实现使用恰当命名的 ButtonBar控制。这记录在DialogPane.createButtonBar()中(强调我的):

This method can be overridden by subclasses to provide the button bar. Note that by overriding this method, the developer must take on multiple responsibilities:

  1. The developer must immediately iterate through all button types and call createButton(ButtonType) for each of them in turn.
  2. The developer must add a listener to the button types list, and when this list changes update the button bar as appropriate.
  3. Similarly, the developer must watch for changes to the expandable content property, adding and removing the details button (created via createDetailsButton() method).

The default implementation of this method creates and returns a new ButtonBar instance.

默认情况下,ButtonBar 会将所有按钮的大小调整为最宽按钮的宽度。

Uniform button sizing

By default all buttons are uniformly sized in a ButtonBar, meaning that all buttons take the width of the widest button. It is possible to opt-out of this on a per-button basis, but calling the setButtonUniformSize(Node, boolean) method with a boolean value of false.

If a button is excluded from uniform sizing, it is both excluded from being resized away from its preferred size, and also excluded from the measuring process, so its size will not influence the maximum size calculated for all buttons in the ButtonBar.

正如上面的 Javadoc 中提到的,可以使用静态方法 ButtonBar.setButtonUniformSize(Node, boolean) 禁用此行为。 。只需使用 getButtonTypes()lookupButton(ButtonType) 循环遍历按钮,并将每个按钮的统一大小设置为 false

Alert alert = ...;
DialogPane pane = alert.getDialogPane();
pane.getButtonTypes().stream()
        .map(pane::lookupButton)
        .forEach(btn-> ButtonBar.setButtonUniformedSize(btn, false));

请注意,如果不使用默认值,这要求您事先配置 ButtonType

如果涉及自定义DialogPane,这将变得依赖于实现。例如,自定义 DialogPane 可能不使用 ButtonBar。但是,您的代码没有显示使用自定义 DialogPane 的迹象,因此上述解决方案应该可以正常工作。

关于JavaFX (8) 警报 : different button sizes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45866249/

相关文章:

java - 使用包含 WebView 的投影创建无边框窗口

java - 尝试在我的 Controller 中使用原始版本和全屏版本的 Pane 也会更改窗口版本中的 Pane

JavaFX HBox HGrow 优先级

javafx - 如何在选择和取消选择单元格时轻松自定义 JavaFX ListCell 背景颜色

java - 处理表格 View 中的按钮单击事件

java - 如果我创建新的 javafx 应用程序,如何将 javafx intellij 模板更改为我自己的模板?

Android:对话框关闭而不调用关闭

android - 在 onCreate() 中显示对话框

javascript - Material UI 中的对话框以奇怪的灰色背景打开

java - JavaFx 中的 Jgraph