How do I write a new ListChangeListener<Item>() with lambda?
Asked Answered
L

2

15

How do I write a new ListChangeListener() with lambda in java8?

listItems.addListener(new ListChangeListener<Item>() {
    @Override
    public void onChanged(
        javafx.collections.ListChangeListener.Change<? extends Item> c) {
        // TODO Auto-generated method stub
    }
});

This is what I tried:

listItems.addListener(c->{});

But eclipse states:

The method addListener(ListChangeListener) is ambiguous for the type ObservableList.

The List is declared as:

ObservableList<Item> listItems = FXCollections.observableArrayList();
Loaning answered 28/4, 2014 at 7:56 Comment(0)
D
35

Since ObservableList inherits addListener(InvalidationListener) from the Observable interface, the compiler is unable to determine which version to call. Specifying the type of the lambda through a cast should fix this.

listItems.addListener((ListChangeListener)(c -> {/* ... */}));

You can also explicitly specify the type of c:

listItems.addListener((ListChangeListener.Change<? extends Item> c) -> {/* ... */});
Drainpipe answered 28/4, 2014 at 8:5 Comment(2)
searchResultListItems.addListener((ListChangeListener.Change<? extends Contact> c) ->{}); did the trick thx for the hintLoaning
Cannot do the above option with ChangeListener. Using PropertyListeners... "Lambda expression`s signiture do not match the signature of the functional interface method changed(ObservableValue, Object, Object)". - When trying to: property.addListener((ChangeListener) e -> ({/* ... */}));Uniformize
D
0

This code works without having to specify the types.

listView.focusedProperty ().addListener ( (arg, oldVal, newVal) -> System.out
        .printf ("ListView %s focus%n", (newVal ? "in" : "out of")));
Dreyer answered 5/11, 2016 at 2:30 Comment(1)
Your solution works for ListViews, but the question was about ObservableLists, which do not have a focusedProperty.Turboelectric

© 2022 - 2024 — McMap. All rights reserved.