Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Selection in table view on clicking on empty rows in javafx

I have a TableView with some rows. The user can select any row but when he clicks on empty rows or anywhere on the Stage, I want to clear his current selection of the TableView.

like image 940
Anurag Sharma Avatar asked Jan 28 '17 08:01

Anurag Sharma


People also ask

How to select row in JavaFX?

To select a row with a specific index you can use the select(int) method. Here is an example of selecting a single row with a given index in a JavaFX TableView: selectionModel. select(1);

What is TableView in JavaFX?

The TableView class provides built-in capabilities to sort data in columns. Users can alter the order of data by clicking column headers. The first click enables the ascending sorting order, the second click enables descending sorting order, and the third click disables sorting. By default, no sorting is applied.


1 Answers

You can add a event filter to the Scene that uses the selection model of the TableView to clear the selection, if the click was on a empty row or anywhere outside of a TableView:

scene.addEventFilter(MouseEvent.MOUSE_CLICKED, evt -> {
    Node source = evt.getPickResult().getIntersectedNode();

    // move up through the node hierarchy until a TableRow or scene root is found 
    while (source != null && !(source instanceof TableRow)) {
        source = source.getParent();
    }


    // clear selection on click anywhere but on a filled row
    if (source == null || (source instanceof TableRow && ((TableRow) source).isEmpty())) {
        tableView.getSelectionModel().clearSelection();
    }
});
like image 197
fabian Avatar answered Nov 15 '22 09:11

fabian