java 如何在 HBox 左、中和右对齐子项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41654333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to align children in a HBox Left, Center and Right
提问by Program-Me-Rev
I have a HBoxwith children set up as follows:
我有一个带孩子的HBox,设置如下:
HBox h = new HBox();
h.setMinWidth(555);
Label leftLabel = new Label("Left");
Label centerLabel = new Label("Center");
HBox rightContent = new HBox();
Label r1 = new Label("2");
Label r2 = new Label("3");
rightContent.getChildren().addAll(r1, r2);
h.getChildren().addAll(leftLabel, centerLabel, rightContent);
This will create a HBox with all the children floated on the left. I would like leftLabelto be on the left, centerLabelat the center, and rightContentto the extreme right.
这将创建一个 HBox,所有子项都浮动在左侧。我希望leftLabel位于左侧,centerLabel位于中心,而rightContent位于最右侧。
How can I achieve this?
我怎样才能做到这一点?
Thank you all in advance.
谢谢大家。
回答by Maxim
You can use the following trick:
您可以使用以下技巧:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
public class Main23 extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Label label1 = new Label("Left");
label1.setStyle("-fx-background-color: red; -fx-text-fill: white;");
Label label2 = new Label("Center");
label2.setStyle("-fx-background-color: green; -fx-text-fill: white;");
Label label3 = new Label("Right");
label3.setStyle("-fx-background-color: blue; -fx-text-fill: white;");
Region region1 = new Region();
HBox.setHgrow(region1, Priority.ALWAYS);
Region region2 = new Region();
HBox.setHgrow(region2, Priority.ALWAYS);
HBox hBox = new HBox(label1, region1, label2, region2, label3);
primaryStage.setScene(new Scene(hBox, 640, 240));
primaryStage.show();
}
}
As you can see I just add several Region
controls for fill space between labels and set Hgrow
property to ALWAYS
.
如您所见,我只是添加了几个Region
控件来填充标签之间的空间并将Hgrow
属性设置为ALWAYS
.
This trick is appropriate in some cases because sometimes you can't use other layouts i.e. if you want to align buttons inside of ToolBar
.
这个技巧在某些情况下是合适的,因为有时你不能使用其他布局,即如果你想在ToolBar
.