Search code examples
javaarraylistobservablelist

How do i get an Object of ObservableList in which i can write my own methods?


I'm having the following problem:

I have two Classes named ActiveDateList and MainFrame. The ActiveDateList (written as singleton) is extending Arraylist and holds the currently active "MyDate".

ActiveDateList:

public class ActiveDateList extends ArrayList<MyDate>{

    private static ActiveDateList instance; 

    private ActiveDateList(){}

    public static ActiveDateList getInstance(){
        if(instance == null){
            instance = new ActiveDateList();
        }
        return instance;
    }

...

    public void addSorted(MyDate md){
    ...
    }
}

The MainFrame Class is a JavaFX Application which needs to use an ObservableList of "ActiveDateList".

Code to do so:

    ActiveDateList activeDatelist = ActiveDateList.getInstance();
    ObservableList<MyDate> observableADList = FXCollections.observableList(list);

However after doing so, I lose access to every self written method I have in ActiveDateList, because things like "addSorted" can not be accessed through the ObservableList and every time I only call activeDateList.addSorted(..) observableADList does obviously not notify the listener.

I feel like I need a Class which implements ObservableList and instead of having to override all the methods it just uses the ones from ArrayList class and leaves me the possibility to write my own methods in it.

I am thankful for every idea.


Solution

  • You should be able to extend the javafx.collections.ModifiableObservableListBase class instead of ArrayList. You can then use the beginChange and endChange methods to notify listeners. See: https://docs.oracle.com/javase/8/javafx/api/javafx/collections/ObservableListBase.html#beginChange--