Chris Smith
Chris Smith

Reputation: 3012

Need to Bindings.equals ObservableList

I am new to JavaFX Properties and Bindings. So what I am trying to do is get a BooleanBinding from Bindings.equals() and pass two ObservableLists. I am not sure what kind of list to use here, I need the list to work with a ListView. I have looked through the maze of list properties on the JavaDocs with no luck of any help here.

I need to bind two lists to a BooleanBinding:

BooleanBinding listsEqual = Bindings.equal(list1, list2);

I also need these two lists to work in a ListView:

ListView listView = new ListView();
listView.setItems(list1);

The purpose of the two different lists is to have one list be the current one, and the other be the original version to see if the first one has changed. That isn't really important but I know I need two of them.

My problem is I can't find a list implementation that works with Bindings.equal() and ListView at the same time.

Upvotes: 2

Views: 600

Answers (1)

James_D
James_D

Reputation: 209684

Use

ObservableList<?> list1 = ... ;
ObservableList<?> list2 = ... ;

BooleanBinding listsEqual = Bindings.createBooleanBinding(() -> Objects.equals(list1, list2), 
    list1, list2);

For example:

ListView<String> listView = new ListView<>();
ObservableList<String> list = FXCollections.observableArrayList();
BooleanBinding listsEqual = Bindings.createBooleanBinding(() -> 
    Objects.equals(listView.getItems(), list),
    listView.getItems(), list);
listsEqual.addListener((obs, wereEqual, areNowEqual) -> System.out.println("Lists equal? "+areNowEqual));
System.out.println("Adding to Listview: One");
listView.getItems().add("One");
System.out.println("Adding to list: One");
list.add("One");
System.out.println("Adding to Listview: Two");
listView.getItems().add("Two");
System.out.println("Adding to Listview: Three");
listView.getItems().add("Three");
System.out.println("Adding to list: Two");
list.add("Two");
System.out.println("Adding to list: Three");
list.add("Three");

Upvotes: 3

Related Questions