Reputation: 6624
I have a HBox with children set up as follows:
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 leftLabel to be on the left, centerLabel at the center, and rightContent to the extreme right.
How can I achieve this?
Thank you all in advance.
Upvotes: 12
Views: 23048
Reputation: 9961
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
.
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
.
Upvotes: 25