Multi select in tableView javafx

2020-04-12 00:01发布

问题:

I want to multi select row in my TableView. The problem is that my application is a multitouch application, I have not a keyboard, so not a CTRL key.

I have a code follow :

tableViewArticle.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

But I want to select a lot of row only with a mouse click. For exemple, when I selected one row, the row change in blue, and if after I select an other row, I have two rows in blue.

回答1:

You could use a custom event filter for the TableView that handles the selection, if a click happened on a table row:

tableViewArticle.addEventFilter(MouseEvent.MOUSE_PRESSED, evt -> {
    Node node = evt.getPickResult().getIntersectedNode();

    // go up from the target node until a row is found or it's clear the
    // target node wasn't a node.
    while (node != null && node != tableViewArticle && !(node instanceof TableRow)) {
        node = node.getParent();
    }

    // if is part of a row or the row,
    // handle event instead of using standard handling
    if (node instanceof TableRow) {
        // prevent further handling
        evt.consume();

        TableRow row = (TableRow) node;
        TableView tv = row.getTableView();

        // focus the tableview
        tv.requestFocus();

        if (!row.isEmpty()) {
            // handle selection for non-empty nodes
            int index = row.getIndex();
            if (row.isSelected()) {
                tv.getSelectionModel().clearSelection(index);
            } else {
                tv.getSelectionModel().select(index);
            }
        }
    }
});

If you want to handle touch events differently to mouse events, you can also use MouseEvent.isSynthesized to check, if the event is a touch event.