javafxarraylistchangelistener

JavaFX - Listen to Changes in List


Hi I have a probably quite stupid question. I have just started to play around with Properties and ChangeListeners but have hit a speed bump. I have understood that if I make an ObjectProperty containing an ArrayList any ChangeListener will only fire if the ArrayList itself changes. However I want all ChangeListeners to fire if

  1. The ArrayList itself changes.
  2. The length of the ArrayList changes (that is an element is added or removed).
  3. An element in the ArrayList is changed to a different one.
  4. An element in the ArrayList changes, that is the content of an element changes (If the element is a custom class Person for instance. I want to fire the ChangeListener if the person changes her age for instance.).

Is there some functionality in JavaFX for this already or should I implement this manually? What would be the best way to do this?

/Thanks for any help!


Solution

  • You cannot add a listener to a regular ArrayList as it is not observable. However, the FXCollections package does provide an ObservableArrayList<E> that allows you to listen for changed.

    Here is a demo program:

    import javafx.collections.FXCollections;
    import javafx.collections.ListChangeListener;
    import javafx.collections.ObservableList;
    
    public class Main {
    
        public static void main(String[] args) {
            ObservableList<String> strings = FXCollections.observableArrayList();
    
            strings.addAll("One", "Two", "Three");
    
            strings.addListener((ListChangeListener<String>) change -> {
                while (change.next()) {
                    if (change.wasAdded()) {
                        System.out.println(change.getAddedSubList().get(0)
                                + " was added to the list!");
                    } else if (change.wasRemoved()) {
                        System.out.println(change.getRemoved().get(0)
                                + " was removed from the list!");
                    }
                }
            });
    
            strings.add("Dogs");
            strings.remove("Two");
        }
    }
    

    There are more methods within the ListChangeListener that you can use to get more details about what has been changed. Just read up on it!