TableColumn prefWidth

Viewed 159

I have a TableView in my code for which I am saving the index and width of each TableColumn when the application shuts down (values are saved to a Properties file). When I start the application again, I want to reset the index and width of each TableColumns back to what is was when the application was shut down.

        // If all columns are known, reorder the columns and set the width
        if (allKnown) {
            ObservableList<TableColumn<T, ?>> columns = FXCollections.observableArrayList();

            // Column order and width
            TableColumn<T, ?> column;
            for (int i = 0; i < colIndex.length; i++) {
                column = getOriginalColumns().get(colIndex[i]);
                column.setPrefWidth(colWidths[i]);
                columns.add(column);
            }
            getTableView().getColumns().setAll(columns);
        }
        getTableView().setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

Setting the index works correctly, the column is set in the correct location of the TableView. However, this does not work for the column's prefWidth (all columns are resizable). I have looked at different fora and the culprit seems to be the CONSTRAINED_RESIZE_POLICY. I want to keep that option, since the main screen of my application can be resized. If I use unconstrained, the width works, but then I loose the ability to auto-scale the TableView when the application's main window resizes.

Has anyone experienced the same and found a solution? Your help is greatly appreciated.

1 Answers

The only solution I have found is to initially set the minWidth instead of the prefWidth. then a few pulses after showing the UI, fix the minWidth so column resizing works normally again.

Related