Search code examples
javafxtableviewobservablelist

JavaFX 8 update TableView after new Data added


My TableView is not updating, do i need a listener ? (m is my Model)

@FXML
private TableView<Mitarbeiter> mitarbeiter;

ObservableList<Mitarbeiter> data =
                FXCollections.observableArrayList(m.getMitarbeiterListe()
                );

mitarbeiter.setItems(data);

public ArrayList getMitarbeiterListe(){
    return mitarbeiterliste;
}

In a new Stage i add some Mitarbeiter to the List in my Model

m.addMitarbeiterToList(mitarbeiter)

public void addMitarbeiterToList(Mitarbeiter mitarbeiter){
    mitarbeiterliste.add(mitarbeiter);
}

But the TableView in the other Stage is not updating the new data. In the end, is the ObservableList not pointed to the ArrayList from the Model ?


Solution

  • Instead of adding items to mitarbeiterliste (which is an ArrayList, and is not observable), add them to data, which is the ObservableList holding the items for the table. The TableView observes this list and automatically updates the view when the list contents changes.

    The context of your code snippets is not very clear, but you would do something like

    public ArrayList getMitarbeiterListe(){
        return data;
    }
    

    or instead of

    mitarbeiterliste.add(mitarbeiter); 
    

    do

    data.add(mitarbeiter);