3

My application contains a TableView. Depending on the value of a specific cell in each row, the row style is changed by setting a custom cell factory with setCellFactory for this column. This works fine.

Now I'd like to add a tooltip which is no big deal using setTooltip(). However this tooltip shall be set for every cell in the table, not just the column it is specified for. How can I implement this?

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

1 Answers1

14

Once the table is set up (i.e. the columns are created and added, and the cell factories are set on all the columns), you can "decorate" the columns' cell factories:

private <T> void addTooltipToColumnCells(TableColumn<TableDataType,T> column) {

    Callback<TableColumn<TableDataType, T>, TableCell<TableDataType,T>> existingCellFactory 
        = column.getCellFactory();

    column.setCellFactory(c -> {
        TableCell<TableDataType, T> cell = existingCellFactory.call(c);

        Tooltip tooltip = new Tooltip();
        // can use arbitrary binding here to make text depend on cell
        // in any way you need:
        tooltip.textProperty().bind(cell.itemProperty().asString());

        cell.setTooltip(tooltip);
        return cell ;
    });
}

Here just replace TableDataType with whatever type you used to declare your TableView, i.e. this assumes you have

TableView<TableDataType> table ;

Now, after you have created the columns, added them to the table, and set all their cell factories, you just need:

for (TableColumn<TableDataType, ?> column : table.getColumns()) {
    addTooltipToColumnCells(column);
}

or if you prefer a "Java 8" way:

table.getColumns().forEach(this::addTooltipToColumnCells);
Robert Strauch
  • 12,055
  • 24
  • 120
  • 192
James_D
  • 201,275
  • 16
  • 291
  • 322
  • 1
    One slight issue with this is that it shows "null" for empty cells, which isn't very elegant (especially for non-technical users). One way to overcome this is to bind the `tooltip` property to a binding that takes cell status into account: `cell.tooltipProperty().bind(Bindings.when(Bindings.or(cell.emptyProperty(), cell.itemProperty().isNull())).then((Tooltip) null).otherwise(tooltip));` – Itai Jul 16 '17 at 10:38