Setting a tooltip on all table cells in JavaFX

2019-05-13 07:31发布

问题:

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?

回答1:

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);