Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unselect a selected table row upon second click/selection in javaFX

On my JavaFX table, when I click on a row, it selects that row. Now when I click for the second time on same row which was previously selected, I want to deselect that particular row. Is it possible ? Please share some example code, if its possible.

like image 591
Dil Avatar asked Oct 21 '13 09:10

Dil


1 Answers

Below piece of code worked for this requirement.

tableView.setRowFactory(new Callback<TableView<Person>, TableRow<Person>>() {  
        @Override  
        public TableRow<Person> call(TableView<Person> tableView2) {  
            final TableRow<Person> row = new TableRow<>();  
            row.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() {  
                @Override  
                public void handle(MouseEvent event) {  
                    final int index = row.getIndex();  
                    if (index >= 0 && index < tableView.getItems().size() && tableView.getSelectionModel().isSelected(index)  ) {
                        tableView.getSelectionModel().clearSelection();
                        event.consume();  
                    }  
                }  
            });  
            return row;  
        }  
    });  

Used the same Person class from oracle's table view example. Original answer was given by @James_D in oracle's forum.

like image 75
Dil Avatar answered Jan 04 '23 05:01

Dil