holothuroid
holothuroid

Reputation: 391

JavaFX Treeview return selected items

I'd like to get the selection in a TreeView and have the corresponding model object returned. All answers about this suggest that this done with an inner class or lambda expression. However, when I do this compiler reminds me that variables have to be (effectively) final. I understand, why that is so, but I do not know solve the issue.

Note: I'm actually not sure, why the situation would require a listener in the first place, as I don't even want to listen constantly but get the result, when the method is called.

    private CampaignObject getLeadSelect(){
    CampaignObject co = null;

    campTree.getSelectionModel().selectedItemProperty().addListener(
        new ChangeListener<TreeItem <CampaignObject>>() {
            @Override
            public void changed(ObservableValue<? extends TreeItem<CampaignObject>> observableValue, 
                    TreeItem<CampaignObject> oldItem, TreeItem<CampaignObject> newItem) {
                    co = newItem.getValue());
        }
    });

    return co;
}

Upvotes: 2

Views: 8528

Answers (1)

James_D
James_D

Reputation: 209694

If you don't need a listener, don't define one. It sounds like you just need

private CampaignObject getLeadSelect(){
    TreeItem<CampaignObject> selectedItem = campTree.getSelectionModel().getSelectedItem();
    return selectedItem == null ? null : selectedItem.getValue() ;
}

If you have multiple selection enabled and want a list of the model objects that are selected, do

private List<CampaignObject> getAllSelected() {
    return campTree.getSelectionModel().getSelectedItems()
           .stream()
           .map(TreeItem::getValue)
           .collect(Collectors.toList());
}

If you want to observe the selected item as the model object, you can do something like:

ObjectProperty<CampaignObject> selectedCampaign = new SimpleObjectProperty<>();
selectedCampaign.bind(Bindings.createObjectBinding(() -> {
    TreeItem<CampaignObject> selectedItem = campTree.getSelectionModel().getSelectedItem();
    return selectedItem == null ?  null : selectedItem.getValue();
}, campTree.getSelectionModel().selectedItemProperty()));

and then you can do things like

selectedCampaign.addListener((obs, oldCampaign, newCampaign) -> {
    // ...
});

Upvotes: 7

Related Questions