Mike Bechtel
Mike Bechtel

Reputation: 33

JavaFX ObservableList binding to sublist

I have two ObservableLists

    public static ObservableList<ImageData> datas_all, datas_flickr;

All objects in datas_flickr are contained in datas_all (datas_flickr is a subset of datas_all). I have a GUI with two different tabs. Both tabs contain TableViews. One TableView shows data from datas_all and other TableView shows datas from datas_flickr.

Both Tabs have a delete-Button which deletes the object which is selected in the corresponding TableView. Now I am wondering if there is any easy way to bind objects in datas_flickr with their corresponding objects in datas_all?

Upvotes: 0

Views: 2812

Answers (1)

ItachiUchiha
ItachiUchiha

Reputation: 36792

Bidirectional Binding won't work in your case, as it needs the ObservableList to contain same data

You can achieve this by using the ListChangeListener on the datas_flickr

Working Sample

import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

public class SubListBinding {

    public static void main(String[] args) {
        ObservableList<String> list = FXCollections.observableArrayList();
        ObservableList<String> subList = FXCollections.observableArrayList();
        list.addAll("a", "b", "c");
        subList.addAll("x", "y", "z");
        list.addAll(subList);
        subList.addListener(new ListChangeListener<String>() {
             public void onChanged(Change<? extends String> c) {
                 while (c.next()) {
                     if (c.wasPermutated()) {
                         for (int i = c.getFrom(); i < c.getTo(); ++i) {
                              //permutate
                         }
                     } else if (c.wasUpdated()) {
                              //update item
                     } else {
                         for (String remitem : c.getRemoved()) {
                             list.remove(remitem);
                         }
                         for (String additem : c.getAddedSubList()) {
                             list.add(additem);
                         }
                     }
                 }
             }
         });
        System.out.println("Before removal..");
        System.out.println("List : " + list);
        System.out.println("SubList : " + subList);
        System.out.println("After removal..");
        subList.remove("y");
        System.out.println("List : " + list);
        System.out.println("SubList : " + subList);
    }

}

Similarly, you can do the same on datas_all

Upvotes: 3

Related Questions