javafx column in tableview does not fit prefWidth

701 Views Asked by At

I would like to restore the column width of every column in my TableView after a restart of my javaFX application. Therefore I read an article which discribes how to achive this. Unfortunately the code did not work for me. The columns do not resize after the restart. (But the values for width and prefWidth did change correctly)

Article - How to remember the width of TableColumns

I already did some reading but was not able to solve this problem:

The resize policy for my table is set to CONSTRAINED_RESIZE_POLICY and this seems to be the problem. If I switch to UNCONSTRAINED_RESIZE_POLICY the columns get resized. But as I want the columns not to disappear when the user changes the columnwidth, I would like to stay with the constrained resize policy.

Any help would be greatly appreciated. Many thanks in advance.

1

There are 1 best solutions below

0
On

It's an old question and it's not clear what is being asked here, but I was having a similar problem (I guess) with setting the prefWidth of a TableColumn, which wouldn't work. So I looked into JavaFX code and I found that prefWidth is handled like this:

private final DoubleProperty prefWidth = new SimpleDoubleProperty(this, "prefWidth", DEFAULT_WIDTH) {
        @Override protected void invalidated() {
            doSetWidth(getPrefWidth());
        }
    };

So I realized that the doSetWidth method was not being called because the width had changed, but not prefWidth. This happens for example when the user manually resizes the column.

It can be fixed simply by listening to width property and setting prefWidth, like this:

for (TableColumn col : getColumns()) {
    col.setPrefWidth(col.getWidth());
}