Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to deselection of row in JavaFX tableview?

I have a tableview with SelectionMode.MULTIPLE:

    table.setEditable(true);
    table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

    table.getSelectionModel().selectedItemProperty().addListener(
            (observable, oldValue, newValue) -> {
                table.getSelectionModel().getSelectedItems().forEach(System.out::println);
            });

Selecting rows works finde, but if a deselect a row again (by clicking ctrl+left-click) the listener doesn't react to that immediately. What I have to do to deselect a row is the following:

  1. Select lets say 'Rob', 'Peter', 'Max' and 'John' (Either by selecting them individualy with ctrl+left-click or all of them together by shift+left click)
  2. Unselect 'Peter' by clicking ctrl+left-click (now this row has a weird blue border and the listener didn't detected the change)
  3. Deselect another row (Now this row has this weird border and 'Peter' is row looks normal)
  4. Reselect the previous row (Now the listener detects that I unselected 'Peter')
    enter image description here
like image 848
haisi Avatar asked Mar 18 '23 07:03

haisi


1 Answers

According to the javadocs the selectedItem property in multiple selection mode refers to the last item selected:

The selected item property is most commonly used when the selection model is set to be single selection, but is equally applicable when in multiple selection mode. When in this mode, the selected item will always represent the last selection made.

In your scenario, if you select "Rob", "Peter", "Max" and "John", in that order, then the selected item ends up as the last person selected ("John"), and the selected items list contains all four items. When you deselect "Peter", the last item selected is still "John". Since the selectedItem hasn't changed, your change listener is not invoked. When you deselect another item and then reselect it, the last selected item changes to that item, and your listener is invoked.

The "weird" border you see is simply the table's display for a cell with focus (you just clicked on it) which is not selected.

To see all the changes to the selected items, you need to register a ListChangeListener with the list of selected items:

table.getSelectionModel().getSelectedItems().addListener((Change<? extends Person> change) -> 
    System.out.println(table.getSelectionModel().getSelectedItems());
like image 192
James_D Avatar answered Mar 31 '23 21:03

James_D