我正在使用 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,...);
结果:
现在每个项目的宽度相同,但文本对齐方式现在似乎居中。我尝试通过 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);
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/