Search code examples
javafxmouseeventcell

Get TableView cell data using MouseEvent


I currently have a TableView with a custom CellFactory. I am trying to figure out how to get the core data underlying a cell when the mouse enters that cell.

I will be using this data to populate a label that is defined in another controller.

I've been trying to look at event filters and event handlers, and suspect the answer has something to do with using those appropriately, but I haven't been able to figure this out or find an answer.

Please let me know what code, if any, you would like to see. I am not even sure what would help at this point.


Solution

  • Register a mouse listener with the cell to handle mouseEntered events, and call getItem() on the cell to get the data:

    TableView<MyRowType> table = ... ;
    TableColumn<MyRowType, MyCellType> column = ... ;
    
    column.setCellFactory ( c-> {
        TableCell<MyRowType, MyCellType> cell = new TableCell<MyRowType, MyCellType>() {
            @Override
            public void updateItem(MyCellType item, boolean empty) {
                super.updateItem(item, empty) ;
                // your implementation here...
            }
        };
        cell.setOnMouseEntered( e -> {
            MyCellType item = cell.getItem();
            if (item != null) {
                // do whatever you need with item
            }
        });
        return cell ;
    });