首页 > 解决方案 > 自动调整 javafx 大小时,TableView tableColumn 宽度不考虑标题

问题描述

需要帮助解决表格视图 JavaFX 上的显示问题。

我无法粘贴完整的代码。但是,将尝试包括最大值。

TextField headerTextField = new TextField();
Label label = new Label((String) allColumns[i]);
VBox headerGraphic = new VBox();
headerGraphic.setAlignment(Pos.CENTER);
headerGraphic.getChildren().addAll(label, headerTextField);
TableColumn tableColumn = new TableColumn<>();
tableColumn.setGraphic(headerGraphic);

输出是: 在此处输入图像描述

如果我不设置图形,直接创建一个列名的表格列,看起来不错。

TableColumn tableColumn = new TableColumn<>((String) allColumns[i]);

输出是: 在此处输入图像描述

更新: 我通过使用Text而不是Label解决了它。似乎只有在加载场景后才计算标签的宽度。因此,未设置表格列首选项宽度。

使用下面的代码,它起作用了。

TextField headerTextField = new TextField();
Text label = new Text((String) allColumns[i]);
VBox headerGraphic = new VBox();
headerGraphic.setAlignment(Pos.CENTER);
headerGraphic.getChildren().addAll(label, headerTextField);
TableColumn tableColumn = new TableColumn<>();
tableColumn.setGraphic(headerGraphic);

输出是: 在此处输入图像描述

标签: javafxtableviewwidthtablecolumn

解决方案


我通过使用文本而不是标签来解决它。似乎只有在加载场景后才计算标签的宽度。因此,未设置表格列首选项宽度。编辑了上面的帖子。

更新: 我不得不使用调整大小自定义方法,因为当表没有记录时,上述方法不起作用。所以,我调用了下面的函数,它适用于有记录的表和没有记录的表。

public static void autoResizeColumns( TableView<?> table )
    {
        //Set the right policy
        table.getColumns().stream().forEach( (column) ->
        {
            Text t = new Text( column.getText() );
            double max = 0.0f;
            if("".equals(t.getText()))
            {
                VBox vBox = (VBox) column.getGraphic();
                ObservableList<Node> vBoxChild = vBox.getChildren();
                max = vBoxChild.get(0).getLayoutBounds().getWidth();
            }
            else
            {
                max = t.getLayoutBounds().getWidth();
            }
            
            for ( int i = 0; i < table.getItems().size(); i++ )
            {
                //cell must not be empty
                if ( column.getCellData( i ) != null )
                {
                    t = new Text( column.getCellData( i ).toString() );
                    double calcwidth = t.getLayoutBounds().getWidth();
                    //remember new max-width
                    if ( calcwidth > max )
                    {
                        max = calcwidth;
                    }
                }
            }
            //set the new max-widht with some extra space
            column.setPrefWidth( max + 15.0d );
        } );
    }

推荐阅读