java - 在 setHgrow 的上下文中设置内容对齐

标签 java javafx javafx-2 javafx-8

我正在使用 JavaFX-8 构建应用程序。我正在尝试建立一个菜单。每个菜单项都是一个 ToggleButton,所有 ToggleButton 应具有相同的宽度。所以我使用了以下代码片段:

        VBox vbox = new VBox();
        ToggleButton toggleButton = new ToggleButton("MyText");
        HBox hBox = new HBox();
        hBox.getChildren().add(toggleButton);
        HBox.setHgrow(toggleButton, Priority.ALWAYS);
        toggleButton.setMaxWidth(Double.MAX_VALUE);
                            [...]
        vbox.getChildren().add(hBox,hbox2,hbox3,...);

结果:

snipped of the result of the shown code

现在每个项目的宽度相同,但文本对齐方式现在似乎居中。我尝试通过 toggleButton.setContentDisplay(ContentDisplay.LEFT)toggleButton.setAlignment(Pos.CENTER_LEFT) 将对齐方式更改为 LEFT,但没有成功。还有其他方法可以解决这个问题吗?

更新: 我尝试了 toggleButton.setTextAlignment(TextAlignment.LEFT); ,结果与以前相同。

最佳答案

Labeled 及其子类中有多种控制对齐的机制:

alignmentProperty()这里就是你想要的那个。根据文档,它:

Specifies how the text and graphic within the Labeled should be aligned when there is empty space within the Labeled.

所以你只需要

toggleButton.setAlignment(Pos.CENTER_LEFT);

textAlignmentProperty

Specifies the behavior for lines of text when text is multiline Unlike contentDisplayProperty() which affects the graphic and text, this setting only affects multiple lines of text relative to the text bounds.

换句话说,如果有多行文本,您可以将整个文本视为占据一个矩形,其高度以所有行为界,宽度以最宽的行为界。 textAlignment 属性指定每行在该矩形内的对齐方式。这不适用于您的情况,因为您只有一行文本。

最后,还有 contentDisplayProperty() 。这个

Specifies the positioning of the graphic relative to the text.

因此,只有当按钮中同时显示文本和图形时才会产生影响。例如,将其设置为 ContentDisplay.LEFT 指定图形应放置在文本的左侧。

关于java - 在 setHgrow 的上下文中设置内容对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31657917/

相关文章:

java - 为什么 Eclipse 说 null 是原始类型?

java - 牌组中找到的最高值(value)的卡牌

ssl - 在 JAVA 中发出 HTTPS 请求并打开 SSL 套接字

java - 对 TableView 列进行排序 : a way to bypass an "unsorted" mode

image - 如何裁剪和调整 JavaFX 图像的大小?

java - 使用 java 从图像中提取文本

java - 打印字节时的内存

css - 如何更改 javafx 中特定 TreeView 的折叠和展开图标?

java - 来自 ListView.getItems().removeAll() 的可疑行为

menu - JavaFX 2.0 像 MenuItem 一样激活菜单