java - 在单个 hbox 中为 2 个元素提供单独的对齐方式

标签 java javafx alignment hbox borderpane

我试图获取 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);

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

borderpane 布局现在对于我的项目来说是必需的,但就目前而言,是否有某种方法可以强制标签 tst 保留在 hbox 的最右侧,而 bt1 保留在最左侧?

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

最佳答案

您需要将左侧节点添加到 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);
    }

}

enter image description here

关于java - 在单个 hbox 中为 2 个元素提供单独的对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43562409/

相关文章:

java - 难以在 Java 中将数组转换为缓冲图像

java - List<Long> 如何引用具有 BigInteger 值的 ArrayList

java - 使用 ArrayList 存储变量

java - 将日期和时间添加到文件名

android - 在 TableLayout 中右对齐

java - 使用 JavaFX 打印节点

java - javafx SelectionMode Single 和 Multiple 有什么区别?

JavaFX 2.2 : How to implement a new Chart that extends LineChart

html - 如何将不同高度的元素与表格单元格的顶部和底部对齐?

css - 在 div 中垂直居中列表