How to listen for a selection change in a JavaFX ListView
Asked Answered
A

1

6

I've been searching for a while now and I haven't found anything that works. I want to make it so that every time the user clicks a new client in my list, the clients details are presented in the fields (see screenshot below):

Client screen

After scrapping a bunch of solutions I found online that didn't work, here is my basic code so far:

@FXML
private ListView<Client> clientList;
private ObservableList clientObservableList;

@Override
public void initialize(URL url, ResourceBundle rb) {
    this.initializeGymState();//this loads in some dummy clients
    clientObservableList = FXCollections.observableArrayList(gym.getClients());
    clientList.getItems().setAll(clientObservableList);
    clientList.getSelectionModel().selectFirst();
    this.clientDisplayDetails();//this displays the client details, works fine
}

I don't even know where to start with this solution, the reason I have an ObservableList in there is because I hoped to use a ListChangeListener, but now I think the ListChangeListener can listen for a change in the list (add, rmove, etc.), NOT a change in the selection. I'm new to JavaFX so talk to me like I'm a 5 yr old child please :P

Thanks guys

Architect answered 10/2, 2017 at 20:48 Comment(0)
R
13

For single selection:

clientList.getSelectionModel().selectedItemProperty().addListener(...);

For multiple selection:

clientList.getSelectionModel().getSelectedItems().addListener(...);
Romeyn answered 10/2, 2017 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.