【问题标题】:javafx gridpane center align and justify all labelsjavafx gridpane中心对齐并对齐所有标签
【发布时间】:2017-04-18 19:26:59
【问题描述】:

这个想法是创建一个提交表单,其中包含许多标签居中和对齐,例如:

标签 1 是 客户名称,标签 2 是 产品名称 我想做的是水平居中对齐所有标签,这很容易,但同时我希望他们有道理。简而言之,P 应该正好在网格窗格第二行的 C 之下。

【问题讨论】:

    标签: java javafx alignment label gridpane


    【解决方案1】:

    请注意,每列中最宽的节点负责确定起始 x 坐标。如果节点居中,则需要将所有节点移动节点宽度差的一半到左边的最大宽度,这可以使用translateX属性来实现:

    示例

    @Override
    public void start(Stage primaryStage) {
        GridPane gp = new GridPane();
        ColumnConstraints constraints = new ColumnConstraints();
        constraints.setHalignment(HPos.CENTER);
        constraints.setPercentWidth(50);
    
        gp.getColumnConstraints().addAll(constraints, constraints);
        Random random = new Random();
    
        Node[][] elements = new Node[2][10];
    
        for (int x = 0; x < elements.length; x++) {
            final Node[] column = elements[x];
            InvalidationListener sizeListener = o -> {
                // determine max width
                double maxSize = 0;
    
                for (Node n : column) {
                    double width = n.getLayoutBounds().getWidth();
                    if (width > maxSize) {
                        maxSize = width;
                    }
                }
    
                // adjust translate
                for (Node n : column) {
                    n.setTranslateX((n.getLayoutBounds().getWidth() - maxSize) / 2);
                }
            };
    
            // fill column with strings of random lenght
            for (int y = 0; y < 10; y++) {
                int charCount = random.nextInt(30);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < charCount; i++) {
                    sb.append('a');
                }
                Label text = new Label(sb.toString());
                text.layoutBoundsProperty().addListener(sizeListener);
                column[y] = text;
            }
            gp.addColumn(x, column);
            sizeListener.invalidated(null);
        }
    
        Scene scene = new Scene(gp);
    
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    

    编辑

    即使您无法使用 SceneBuilder 执行此操作,您也可以将这种对齐方式应用到 f​​xml 中的 GridPane,如果您实现了在实用程序类中添加此功能并使用 fxml 中的实用程序类的逻辑。

    public final class WeirdAlign {
    
        private WeirdAlign() {
        }
    
        public static final Predicate<Node> ALL_PREDICATE = n -> true;
    
        public static void setCombinedCenterJustify(GridPane gridPane, Predicate<Node> predicate) {
            InvalidationListener listener = o -> {
                Node n = (Node) ((ReadOnlyProperty) o).getBean();
                updateGridPaneColumn(gridPane, getGridPaneColumn(n), predicate);
            };
            ObservableList<Node> children = gridPane.getChildren();
    
            for (Node n : children) {
                if (predicate.test(n)) {
                    n.layoutBoundsProperty().addListener(listener);
                }
            }
    
            int[] columns = children.stream().filter(predicate).mapToInt(WeirdAlign::getGridPaneColumn).distinct().toArray();
            for (int i : columns) {
                updateGridPaneColumn(gridPane, i, predicate);
            }
    
            children.addListener((ListChangeListener.Change<? extends Node> c) -> {
                Set<Integer> columnsToUpdate = new HashSet<>();
                while (c.next()) {
                    if (c.wasRemoved()) {
                        for (Node n : c.getRemoved()) {
                            if (predicate.test(n)) {
                                n.layoutBoundsProperty().removeListener(listener);
                                columnsToUpdate.add(getGridPaneColumn(n));
                            }
                        }
                    }
                    if (c.wasAdded()) {
                        for (Node n : c.getAddedSubList()) {
                            if (predicate.test(n)) {
                                n.layoutBoundsProperty().addListener(listener);
                                columnsToUpdate.add(getGridPaneColumn(n));
                            }
                        }
                    }
                }
                for (Integer i : columnsToUpdate) {
                    updateGridPaneColumn(gridPane, i, predicate);
                }
            });
        }
    
        /**
         * This method is only here for FXMLLoader.
         */
        public static Predicate<Node> getCombinedCenterJustify(GridPane node) {
            throw new UnsupportedOperationException();
        }
    
        public static void updateGridPaneColumn(GridPane gridPane, int column, Predicate<Node> predicate) {
            double maxSize = 0;
            for (Node child : gridPane.getChildren()) {
                if (column == getGridPaneColumn(child) && predicate.test(child)) {
                    double width = child.getLayoutBounds().getWidth();
                    if (width > maxSize) {
                        maxSize = width;
                    }
                }
            }
            for (Node child : gridPane.getChildren()) {
                if (column == getGridPaneColumn(child) && predicate.test(child)) {
                    child.setTranslateX((child.getLayoutBounds().getWidth() - maxSize) / 2);
                }
            }
        }
    
        public static int getGridPaneColumn(Node node) {
            Integer c = GridPane.getColumnIndex(node);
            return c == null ? 0 : c;
        }
    
    }
    
    <GridPane xmlns:fx="http://javafx.com/fxml/1" id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.60" >
        <columnConstraints>
            <ColumnConstraints fx:id="c1" fillWidth="false" halignment="CENTER" percentWidth="50.0" />
            <fx:reference source="c1"/>
        </columnConstraints>
       <children>
          <Label text="abfkaenlgen" />
          <Label text="z7492z4z58z4zu uzu53 9zu59h 5n 54uhn" GridPane.columnIndex="1" GridPane.rowIndex="2" />
          <Label text="bbdnfkbner" GridPane.columnIndex="1" GridPane.rowIndex="1" />
          <Label text="hhhhhddddssaaeeeaaae" GridPane.rowIndex="1" />
          <Label text="gjnwkeibrgbawhgbreökbrgesöbrgsnrgs" GridPane.rowIndex="2" />
       </children>
       <WeirdAlign.combinedCenterJustify>
           <WeirdAlign fx:constant="ALL_PREDICATE"/>
       </WeirdAlign.combinedCenterJustify>
    </GridPane>
    

    【讨论】:

    • 如果我使用场景构建器创建了 UI,上面的代码可能需要进行哪些更改
    • @Takasur 由于这不支持标准对齐方式,因此您不能简单地在 SceneBuilder 中进行设置。不过,您可以使用静态方法将这种行为添加到 GridPane,请参阅我的编辑。
    猜你喜欢
    • 2016-05-28
    • 2019-04-14
    • 2016-07-31
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    相关资源
    最近更新 更多