I would like to set the size of a JavaFx TableView such that all rows are visible without the need to scroll. ie the TableView should not be any larger or smaller than needed to display all rows without scrolling. I am using a custom TableCellFactory to adjust the height of the rows since some cells will have wrapped text, so not all rows are the same height.
I first attempted to do this in the custom TableCellFactory adding the TableRow to a set, and then creating a getTableHeight method which could be called to determine the total height of all the rows. However, what appears to be happening is that only rows that are initially visible are added to the set, and not all the rows, so the height calculation is not coming out correctly.
Is there a better way to go about doing this?
public class FormattedTableCellFactory<S, String> implements Callback<TableColumn<S, String>, TableCell<S, String>> {
public FormattedTableCellFactory() {
}
protected Set<TableRow> tableRowSet = new HashSet<>();
public double getTableHeight() {
double total = 0;
Iterator<TableRow> iterator = tableRowSet.iterator();
while( iterator.hasNext() ) {
double height = iterator.next().getHeight();
total += height;
}
return total;
}
/**
* set Tooltip and enable WordWrap for Description column
* @param p
* @return
*/
@Override
public TableCell<S, String> call(TableColumn<S, String> p) {
TableCell<S, String> cell = new TableCell<S, String>() {
{
tableRowSet.add(this.getTableRow() );
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
Tooltip tooltip = new Tooltip(item.toString());
this.setText(item.toString());
setTooltip(tooltip);
Text text = new Text(item.toString());
text.wrappingWidthProperty().bind(widthProperty());
text.textProperty().bind(textProperty());
this.setWrapText(true);
this.setGraphic(text);
this.setAlignment(Pos.TOP_LEFT);
this.setHeight(text.getWrappingWidth());
} else {
this.setText(null);
}
}
};
return cell;
}
}