JavaFX, columns in TableView resize after been mov

2019-08-25 04:26发布

问题:

I have a TableView with a number of columns that exceeds the screen width. When it's loaded the first time, all columns have the same width but, as soon as I move one of these, all of them are resized to a width equals to the maximum width of data inside the cells of the column.

My question is: is it possible to disable this behavior or to make it works till the first load of the TableView?

PS: the TableView is loaded empty, then pressing a button it is filled with data, because you have some key field to input before sending the request for data.

回答1:

When it's loaded the first time, all columns have the same width but, as soon as I move one of these, all of them are resized to a width equals to the maximum width of data inside the cells of the column.

This behaviour is kind of weird. I am not sure if it is as intended or if it is a bug. If you think it is a bug, file it in the JavaFX bug tracker.

I assume by move that you mean that you click on a table header and drag the column to another position to reorder columns.

There seems to be (at least) two ways to fix it so that the user specified column width is kept after a column move.

A. Using a CONSTRAINED_RESIZE_POLICY (mostly) fixes it.

table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

OR

B. Bind the prefWidth of each column to it's actual width.

firstNameCol.prefWidthProperty().bind(firstNameCol.widthProperty());


回答2:

After some tests I found that the reason of the behaviour described was: not explicity setting the column prefWidth.

If you create a Tableview with data inside since the beginning and without setting column prefWidth, all columns width will match the data maximum width and, if you change column width, as soon as you drag one the width will be restored to the original value.

If you create a Tableview with data inside since the beginning and setting column prefWidth, all columns width will match the setted value and if you enlarge a column before dragging one then that column width will remain unchanged.

I have no idea if this is a bug or it is wanted. However thank you jewelsea for the suggestions.