Ширина столбца TableView tableColumn не учитывает заголовок при автоматическом изменении размера javafx - PullRequest
1 голос
/ 21 июня 2020

Требуется помощь, чтобы исправить проблему отображения в табличном представлении 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);

Результат: enter image description here

if I don't set graphics and directly create a table column with a column name, it looks good.

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

Output is: enter image description here

Updates: I resolved it by using Text instead of Label. Seems that Label's width is calculated only after Scene is loaded. Hence, the table column pref width was not set.

With the code below, it worked.

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);

Output is: введите описание изображения здесь

1 Ответ

0 голосов
/ 21 июня 2020

Я решил это, используя текст вместо метки. Кажется, ширина метки рассчитывается только после загрузки сцены. Следовательно, ширина pref столбца таблицы не была установлена. Отредактировал вышеуказанный пост.

Обновления: Мне пришлось использовать настраиваемый метод изменения размера, поскольку указанный выше подход не работал, когда в таблице нет записей. Итак, я вызвал приведенную ниже функцию, и она работала как для таблицы с записями, так и для таблицы без записей.

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 );
        } );
    }
...