Clear table selection when clicking on blank lines in javafx

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

+5
source share
2 answers

You can save the last selected line and check with the mouse on the scene if the click was in the selected line 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(); } } } }); 
+2
source

You can add an event filter to Scene , which uses the TableView selection model to clear the selection if the click was on an empty row or somewhere outside of the 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(); } }); 
+2
source

Source: https://habr.com/ru/post/1263489/


All Articles