Search code examples
javalistjavafxobservablelist

JavaFX ObservableList based elements weird behavior


I have a JavaFX application, which has few elements (one ListView, two ChoiceBox'es) based on same generic type.

@FXML private ListView<Department> departmentList;
@FXML private ChoiceBox<Department> employeeAddDepartment;
@FXML private ChoiceBox<Department> employeeEditDepartment;

I fill them all with one obs. list:

List<Department> ds = db.getDepartmentList();
ObservableList<Department> ds1 = FXCollections.observableArrayList(ds);
departmentList.setItems(ds1);
employeeAddDepartment.setItems(ds1);
employeeEditDepartment.setItems(ds1);

The problem is, when you add an element to one element (for example departmentList)with

departmentList.getItems().add(dep);

, it's automatically added to choiceboxes as well and you get 3 duplicated items in listview and both choiceboxes. Why does that happen? I tried to look obs. list documentation, but didn't find anything related, also searched stackoverflow. I tried to add equals/hashCode methods to Employee class, but looks like it doesn't affect it.

Even more strange is the fact that sometimes that sync stops working. Like, it worked last time you launched it, but today you don't see items added to choiceboxes at all (if you add elements only to one of the element to prevent duplication). So, you try to modify your code and try to add elements to choiceboxes if they're not synced today due some reason. Next, you launch your application and see 3 duplicated items again. You revert your code and now your application works like yesterday. That sounds very weird, but it works like so.

So, the question is why does that happen/not happen randomly and how to disable/enable it to be sure that it will work next launch as expected?


Solution

  • That happens because the 3 components share the same list. Create it like this:

    List<Department> ds = db.getDepartmentList();
    departmentList.getItems().addAll(ds);
    employeeAddDepartment.getItems().addAll(ds);
    employeeEditDepartment.getItems().addAll(ds);