Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 766
bashoogzaad Avatar asked Oct 17 '14 12:10

bashoogzaad


People also ask

How to select a row in JavaFX TableView?

To select a row with a specific index you can use the select(int) method. Here is an example of selecting a single row with a given index in a JavaFX TableView: selectionModel. select(1);

How to select multiple rows in TableView in JavaFX?

I would add a multi-select button like android. Click the button the subsequent selections get added (or maybe removed after another click) to a list of selections.

How to set Data in TableView in JavaFX?

TableView is a component that is used to create a table populate it, and remove items from it. You can create a table view by instantiating thejavafx. scene. control.

How do I filter a TableView?

We can filter TableView content in two main ways – manually, or by using the FilteredList class JavaFX provides. In either case, we can update our search criteria by placing a ChangeListener on the search box TextField. This way, each time the user changes their search, the TableView is updated automatically.


1 Answers

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();     } }); 
like image 134
James_D Avatar answered Sep 24 '22 16:09

James_D