JavaFX:GridPane右边的对齐标签

问题描述 投票:1回答:1

持续数小时,我一直在尝试获得以下结果:DesignGridDesignFinalResult

我的问题是我无法正确对齐TotalPrice标签,我希望它占据2列并对齐到网格的最右边,当标签尺寸变大(向标签添加更多文本)时,我想要它仅在左侧生长,仍与网格右侧对齐!但是似乎没有任何正常工作!

就我而言,当我提高价格时,它不会像我想要的那样保持...

这是带有较小标签文本的结果,在这种情况下,它看起来很完美,价格与右侧完美对齐:result1

但是当我放一个更大的数字时,这是一个不好的结果,您会看到TotalPrice标签未按预期对齐:result2

这是我的带有硬编码字符串的代码,仅供测试:

GridPane grid = new GridPane();

//Delete Button
Button btn = new Button("X");
btn.setPrefWidth(40);
btn.setPrefHeight(40);

//Labels
Label productName = new Label("MaxiCheeseBurger Menu");
Label productPrice = new Label("120 den");
Label productQty = new Label("x1");
Label totalPrice = new Label("120 den");

totalPrice.setMaxWidth(Double.MAX_VALUE);
totalPrice.setAlignment(Pos.CENTER_RIGHT);

//Styling labels
productName.setStyle("-fx-font-size: 14;" +
                     "-fx-font-weight: bold;" +
                     "-fx-text-fill: #707070;");
totalPrice.setStyle("-fx-font-size: 14;" +
                    "-fx-font-weight: bold");

//Setting grid column constraints
for (int i = 0; i < 5; i++) {
    ColumnConstraints col = new ColumnConstraints();
    col.setPercentWidth(100.0 / 5);
    col.setHgrow(Priority.ALWAYS);
    col.setFillWidth(true);
    grid.getColumnConstraints().add(col);
}

//Adding nodes to grid
grid.add(btn, 0, 0, 1, 2);
grid.add(productName, 1, 0, 4, 1);
grid.add(productPrice, 1, 1);
grid.add(productQty, 2, 1);
grid.add(totalPrice, 3, 1, 2, 1);

GridPane.setFillWidth(totalPrice, true);
GridPane.setHalignment(totalPrice, HPos.RIGHT);
grid.setGridLinesVisible(true);

grid.setHgap(3);

rows.getChildren().add(grid);
rows.setSpacing(5);
receipt_section.setContent(rows);
receipt_section.setPadding(new Insets(0, 0, 0, 5));
java javafx gridpane
1个回答
-1
投票

您需要在网格单元上设置对齐方式,而不是标签本身。可以使用GridPane.setHalignment()完成。

© www.soinside.com 2019 - 2024. All rights reserved.