简体   繁体   中英

Binding two ObservableLists of different Objects. (Without EasyBind)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM