问题
I have a question about positioning Text into Bar area.
I created this example:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MainApp extends Application
{
@Override
public void start(Stage stage) throws Exception
{
FlowPane flow = new FlowPane();
flow.setPrefSize(900, 30);
Label label = new Label("Zoom 1.5");
Label labelStat = new Label("Users 7");
Label labelSec = new Label("Connected");
flow.getChildren().addAll(label, labelStat, labelSec);
HBox hb = new HBox();
hb.getChildren().add(flow);
Scene scene = new Scene(hb);
stage.setTitle("JavaFX and Maven");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args)
{
launch(args);
}
}
How I can get this visual result:

In my case I want to resize the main stage and preserve the relative position of the Text. I can change FlowPane with different Layout if there is more suitable component.
回答1:
You may choose to use StackPane
and align its children differently:
@Override
public void start( Stage stage )
{
StackPane flow = new StackPane();
flow.setPrefSize(900, 30);
Label label = new Label("Zoom 1.5");
Label labelStat = new Label("Users 7");
Label labelSec = new Label("Connected");
StackPane.setAlignment( label, Pos.CENTER_LEFT );
StackPane.setAlignment( labelStat, Pos.CENTER );
StackPane.setAlignment( labelSec, Pos.CENTER_RIGHT );
flow.getChildren().addAll(label, labelStat, labelSec);
Scene scene = new Scene(flow);
stage.setScene(scene);
stage.show();
}
回答2:
Another option, if you foresee adding more labels in the future, would be to utilize a spacer (or spring) implementation in an HBox
.
@Override
public void start(Stage primaryStage)
{
HBox hbox = new HBox();
hbox.setPrefSize(900, 30);
Label label = new Label("Zoom 1.5");
Label labelStat = new Label("Users 7");
Label labelSec = new Label("Connected");
Region lSpring = new Region();
HBox.setHgrow(lSpring, Priority.ALWAYS);
Region rSpring = new Region();
HBox.setHgrow(rSpring, Priority.ALWAYS);
hbox.getChildren().addAll(label, lSpring, labelStat, rSpring, labelSec);
Scene scene = new Scene(hbox);
primaryStage.setTitle("HBox Springs");
primaryStage.setScene(scene);
primaryStage.show();
}
来源:https://stackoverflow.com/questions/29849096/position-labels-to-different-sides-in-the-parent-pane