0

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;
    }
}
Andrew LaPrise
  • 3,373
  • 4
  • 32
  • 50
  • I already saw that post and it is not what I'm trying to do. I want to adjust the size of the table, I don't want to add/remove rows from the table. – Rob Terpilowski Sep 17 '15 at 12:18
  • Uluk's answer to the linked duplicate does adjust table size (by setting a preferred size for the table). Albeit, that Uluk's answer assumes a fixed row height. – jewelsea Sep 21 '15 at 23:07

0 Answers0