listvieweventsjavafxonmouseclick

How to fire mouse click event on a JavaFX ListView?


How to fire a single and double mouse click events on the first (or any other) item of a javafx.scene.control.ListView?

I want to receive the event like this:

getListView().setOnMouseClicked(mouseEvent -> {
    switch (mouseEvent.getClickCount()) {
        case 1:
            break;
        case 2:
            break;
    }
});

Solution

  • There seems to be a misunderstanding. Events are not fired on the items of the ListView, but on the ListCells that display the items. ListCells may be constructed dynamically and reused, so there may not be a event target corresponding to a particular item.

    If you get your hands on the correct node, you could however fire an event using Event.fireEvent:

    Node target = ...
    MouseEvent mouseEvent = new MouseEvent(MouseEvent.MOUSE_CLICKED, ...);
    Event.fireEvent(target, mouseEvent);
    

    You could also find the ListCells using lookupAll:

    Set<Node> listCells = listView.lookupAll(".list-cell");
    

    and use ListCell.getItem and ListCell.getIndex to determine the correct one.

    But since the event listener is added to the ListView finding the correct ListCell may not be necessary.