JavaFX8: How to create listener for selection of row in Tableview?

bashoogzaad picture bashoogzaad · Oct 17, 2014 · Viewed 56.9k times · Source

I currently have two tableviews in one screen, which results in both TableViews have rows which the user can select.

Now I want only one row to be selected at the same time (doesn't matter which TableView it is selected from). I was thinking about some kind of listener which deselects the other row when a row is selected. This is my initial setup:

Step 1 Search for a way to bind a method to the selection of a row (there is not something like tableview.setOnRowSelected(method))

Step 2 Create the method which acts like a kind of listener: when a row is selected, deselect the other row (I know how to do this part)

Class1 selectedObject1 = (Class1)tableview1.getSelectionModel().getSelectedItem();
Class2 selectedObject2 = (Class2)tableview2.getSelectionModel().getSelectedItem();

if(selectedObject1 != null && selectedObject2 != null) {
   tableview1.getSelectionModel().clearSelection();
}

So, step one is the problem. I was thinking of an observable list on which a listener can be created, and then add the selected row to the list. When this happens, the listener can call the method. Anyone any clue how to make this?

Any help is greatly appreciated.

Answer

James_D picture James_D · Oct 17, 2014

The selectedItem in the selection model is an observable property, so you should be able to achieve this with:

tableview1.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
    if (newSelection != null) {
        tableview2.getSelectionModel().clearSelection();
    }
});

tableview2.getSelectionModel().selectedItemProperty().addListener((obs, oldSelection, newSelection) -> {
    if (newSelection != null) {
        tableview1.getSelectionModel().clearSelection();
    }
});