javalistviewjavafx-2

Getting selected element from ListView


I modify a ListView with the results from a database search in order to use that selection to make another DB request later on.

I want to get the field value of that ListView. What method can I use for that?

I just thought I can also add an event to the onclick and keep it on an attribute for the controller. Is that acceptable too?


Solution

  • Say with a ListView like this:

    ListView<String> listView = new ListView<String>();
    

    Getting selected element from the ListView:

    listView.getSelectionModel().getSelectedItem();
    

    Tracking (listening to) the changes in the ListView selection:

    listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
        @Override
        public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
            System.out.println("ListView selection changed from oldValue = " 
                    + oldValue + " to newValue = " + newValue);
        }
    });