标签的位置不同侧面父窗格(Position labels to different sides in

2019-10-22 19:42发布

我有一个关于定位文成酒吧区的问题。

我创造了这个例子:

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);
    }
}

我怎样才能得到这个视觉效果:

在我来说,我想调整的主要阶段,并保留文本的相对位置。 如果有更多的合适的组分I可以与不同的布局改变FlowPane。

Answer 1:

您可以选择使用StackPane和不同调整其孩子:

@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();
}


Answer 2:

另一种选择,如果你预见在未来添加更多的标签,将利用在间隔(或弹簧)实现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();
}


文章来源: Position labels to different sides in the parent pane