6

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.

user7291698
  • 1,972
  • 2
  • 15
  • 30
Anurag Sharma
  • 143
  • 6
  • 15

2 Answers2

5

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();
    }
});
fabian
  • 80,457
  • 12
  • 86
  • 114
4

You can store the last selected row, and check with a mouse listener on the scene if the click was on the selected row or somewhere else:

    ObjectProperty<TableRow<MyRowClass>> lastSelectedRow = new SimpleObjectProperty<>();

    myTableView.setRowFactory(tableView -> {
        TableRow<MyRowClass> row = new TableRow<MyRowClass>();

        row.selectedProperty().addListener((obs, wasSelected, isNowSelected) -> {
            if (isNowSelected) {
                lastSelectedRow.set(row);
            } 
        });
        return row;
    });


    stage.getScene().addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            if (lastSelectedRow.get() != null) {
                Bounds boundsOfSelectedRow = lastSelectedRow.get().localToScene(lastSelectedRow.get().getLayoutBounds());
                if (boundsOfSelectedRow.contains(event.getSceneX(), event.getSceneY()) == false) {
                    myTableView.getSelectionModel().clearSelection();
                }
            }
        }
    });
user7291698
  • 1,972
  • 2
  • 15
  • 30
  • Thanks a lot for your answer but I am getting null pointer exception at line stage.getScene().addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler() { – Anurag Sharma Jan 28 '17 at 11:26
  • If you have access to the `scene` object, just replace `stage.getScene()` in the code above with `scene`. Otherwise have a look at this question: http://stackoverflow.com/questions/30464238/javafx-getscene-returns-null – user7291698 Jan 28 '17 at 11:58
  • 1
    yes i had access to stage as well. It is now working fine. Thanks a lot – Anurag Sharma Jan 28 '17 at 12:02