How to monitor changes on objects contained in an ObservableList JavaFX

前端 未结 2 1304
死守一世寂寞
死守一世寂寞 2020-12-17 16:58

I really have difficulties to understand how the ObservableList object is working in JavaFX. I want to monitor if an object in the List has been modified. So fa

相关标签:
2条回答
  • 2020-12-17 17:19

    If you want to monitor changes of the objects inside the list instead of the list itself, then you have to attach listeners to the objects of the list and not to the list.

    Of course to be able to do this, the objects must support this. java.lang.Object does not support this.

    Instead take a look at the ObservableValue interface. Objects that implement this interface support this kind of monitoring you're looking for. The javadoc page of ObservableValue lists all the JavaFX built-in classes that implement this interface (the list is quite looooong).

    Either you have to use any of those, or you have to implement the interface yourself. And add your change listeners to the objects and not to the list.

    0 讨论(0)
  • 2020-12-17 17:33
    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList();
        intList.add(0);
        intList.add(1);
    
        ObservableList<Integer> ob = FXCollections.observableArrayList(intList);
        ob.addListener(new ListChangeListener<Integer>() {
            @Override
            public void onChanged(javafx.collections.ListChangeListener.Change<? extends Integer> c) {
                System.out.println("Changed on " + c);
                if(c.next()){
                    System.out.println(c.getFrom());
                }
    
            }
    
        });
    
        ob.set(0, 1);
    }
    

    The event (c in my case) is the index that the change occurred on (when you do .getFrom()). Also if you print the event out you get a string that tells you exactly what happend. You mistakenly interpret it has a change being done on the list as a whole!

    0 讨论(0)
提交回复
热议问题