Binding two ObservableLists of different Objects. (Without EasyBind)

845 Views Asked by At
ObservableList<String> src = FXCollections.observableArrayList();
ObservableList<Integer> other = FXCollections.observableArrayList();
//Create binding.
src.addAll("1", "2", "3");
System.out.println(other);//Should print [1, 2, 3].

Above I have an idea of what I am trying to do.

As items are added and removed to the src list, the other list is synchronized along with it. Every item in the src list has an equivalent to the items in the other list. The other list contains "translated" values from the src list, of course.

Many have recommended using EasyBind, but I would like to understand how to do this manually first.

1

There are 1 best solutions below

0
On

You could use a listener for this like in this example:

ObservableList<String> src = FXCollections.observableArrayList();
ObservableList<Integer> other = FXCollections.observableArrayList();
// Create binding.
src.addListener(new ListChangeListener<String>() {
    @Override
    public void onChanged(ListChangeListener.Change<? extends String> change) {
        while (change.next()) {
            for (String changedString : change.getList()) {
                other.add(Integer.valueOf(changedString));
            }
        }
    }
});
src.addAll("1", "2", "3");
System.out.println(other); // Prints out [1, 2, 3].

Or you can make a method for adding to List, like:

private void addToList(String s) {
    src.add(s);
    other.add(Integer.valueOf(s));
}

Happy Coding,
Kalasch