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


Question

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.

1
24
10/17/2014 12:46:41 PM

Accepted Answer

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();
    }
});
55
10/17/2014 2:11:52 PM

This question helped me but during experiment in javafx and jfoenix this also works for me.

deleteSingle.addEventHandler(MouseEvent.MOUSE_CLICKED, (e) -> {

            StringProperty selectedItem = table.getSelectionModel().getSelectedItem().getValue().link1;

            System.out.println("That is selected item : "+selectedItem);

            if (selectedItem.equals(null)) {

            System.out.println(" No item selected");


            } else {
                System.out.println("Index to be deleted:" + selectedItem.getValue());

                 //Here was my database data retrieving and selectd
                 // item deleted and then table refresh
                table.refresh();

                return;
            }

        });

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon