【问题标题】:Giving 2 elements seperate alignments in a single hbox在单个 hbox 中给 2 个元素单独对齐
【发布时间】:2017-09-19 14:51:34
【问题描述】:

我正在尝试获取 2 个元素,一个按钮和一个标签,以便在 javafx 中的单个 HBox 中拥有自己的单独对齐方式。到目前为止我的代码:

Button bt1= new Button("left");
bt1.setAlignment(Pos.BASELINE_LEFT);

Label tst= new Label("right");
tst.setAlignment(Pos.BASELINE_RIGHT);

BorderPane barLayout = new BorderPane();
HBox bottomb = new HBox(20);
barLayout.setBottom(bottomb);
bottomb.getChildren().addAll(bt1, tst);

默认情况下,hbox 将两个元素推到左侧,彼此相邻。

现在我的项目需要边框布局,但就目前而言,有没有办法强制标签 tst 留在 hbox 的最右侧,而 bt1 留在最左边?

我也可以做 css,如果 -fx-stylesheet 的东西是这样工作的。

【问题讨论】:

    标签: java javafx alignment hbox borderpane


    【解决方案1】:

    您需要将左侧节点添加到 AnchorPane 中,并使该 AnchorPane 水平增长。

    import javafx.application.*;
    import javafx.scene.*;
    import javafx.scene.control.*;
    import javafx.scene.layout.*;
    import javafx.stage.*;
    
    /**
     *
     * @author Sedrick
     */
    public class JavaFXApplication33 extends Application {
    
        @Override
        public void start(Stage primaryStage)
        {
            BorderPane bp = new BorderPane();
            HBox hbox = new HBox();
            bp.setBottom(hbox);
    
            Button btnLeft = new Button("Left");
            Label lblRight = new Label("Right");
    
            AnchorPane apLeft = new AnchorPane();
            HBox.setHgrow(apLeft, Priority.ALWAYS);//Make AnchorPane apLeft grow horizontally
            AnchorPane apRight = new AnchorPane();
            hbox.getChildren().add(apLeft);
            hbox.getChildren().add(apRight);
    
            apLeft.getChildren().add(btnLeft);
            apRight.getChildren().add(lblRight);
    
            Scene scene = new Scene(bp, 300, 250);
    
            primaryStage.setTitle("Hello World!");
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args)
        {
            launch(args);
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      当您根据 JavaDoc 在 ButtonLabel 上调用 setAlignment() 时:

      指定 Labeled 中的文本和图形应如何显示 当标签内有空白空间时对齐。

      所以它只是ButtonLabel 中文本的位置。但是您需要将ButtonLabel 包装在某个容器中(比如说HBox)并使其填满所有可用空间(HBox.setHgrow(..., Priority.ALWAYS)):

      Button bt1= new Button("left");
      HBox bt1Box = new HBox(bt1);
      HBox.setHgrow(bt1Box, Priority.ALWAYS);
      
      Label tst= new Label("right");
      
      BorderPane barLayout = new BorderPane();
      HBox bottomb = new HBox(20);
      barLayout.setBottom(bottomb);
      bottomb.getChildren().addAll(bt1Box, tst);
      

      【讨论】:

        猜你喜欢
        • 2010-09-20
        • 2021-12-02
        • 1970-01-01
        • 2019-01-13
        • 2021-05-22
        • 2013-11-08
        • 2020-12-07
        • 1970-01-01
        • 2012-06-08
        相关资源
        最近更新 更多