Ollie
Ollie

Reputation: 1702

JavaFX ListView select items from two lists

With one ListView, it is possible to select multiple items from it, with the line:

listView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);

Then retrieve the items selected with:

selectedItems =  listView.getSelectionModel().getSelectedItems();

However, I have two ListViews (listView and listView2) in one window. Is there any way to select items across both these lists (by the user holding down Ctrl and selecting items)?

Edit to clarify: For example, I want to be able to select items 1, 4, 5, and 6, then press Delete. I can hold down Ctrl and select 4, 5, and 6 from list1, then select 1 from list2. However, if I then change my mind, and actually want to just select 8, so I release Ctrl and select 8, then everything in list2 should be deselected.

Screenshot of two populated lists and a button

Upvotes: 1

Views: 902

Answers (2)

Ollie
Ollie

Reputation: 1702

I ended up just creating a listener, that would check if Ctrl was being held down when the user changed what list they were selecting items from:

boolean controlIsDepressed = false;

list1.getSelectionModel().selectedItemProperty().addListener(
    (observable) -> {
                Scene scene = list1.getScene();
                scene.setOnKeyPressed(e -> {
                    if (e.getCode() == KeyCode.CONTROL) {
                        controlIsDepressed = true;
                    }
                });
                scene.setOnKeyReleased(e -> {
                    if (e.getCode() == KeyCode.CONTROL) {
                        controlIsDepressed = false;
                    }
                });
                // Clear the other list if Ctrl is not being held down
                if (!controlIsDepressed) list2.getSelectionModel().clearSelection();
            });

And then similar for list2.

Upvotes: 0

M. le Rutte
M. le Rutte

Reputation: 3563

You can create a custom implementation of the SelectionModel which you'd need to share between both lists and in which implement the selection constraints.

However I doubt you need this, if you have two lists with two selection models, use some selection listener and query both lists my impression is that you have already what you need.

Upvotes: 2

Related Questions