Toni_Entranced
Toni_Entranced

Reputation: 979

Populating and synchronizing a ComboBox with an ObservableMap?

I am using a singleton as a false database of Employee objects.

In this pseudo-database, there is an ObservableMap, utilizing the Employees' social security number as their unique key.

I have ComboBoxes, TableViews, and ListViews I would like to populate with this database, as well as make sure that any changes in the database will reflect in these TableViews,Listviews, etc.

ComboBoxes, TVs, and LVs require an ObservableArraylist, however, so how am I supposed to get that out of a HashMap? I could manually extract values out via an iterator and add them to a new ObservableArraylist, but if any changes are made in the database, I would have to manually adjust the ObservableArraylist too. I'd rather have the synchronization be manual.

Any ideas as to what I am supposed to do?

Edit:

Apparently this worked (I had to be very specific. Also unsure as to why I have to use the wildcard instead of just as a generic parameter.

    employeeMap
            .addListener((
                    MapChangeListener.Change<? extends Integer, ? extends Employee> listener) -> {
                System.out.println("CHANGED");
            });

Upvotes: 0

Views: 777

Answers (1)

James_D
James_D

Reputation: 209330

This is not tested, but try something like:

ObservableMap<String, Employee> employeeMap = DataBase.getInstance().getEmployeeMap();
ListView<Employee> listView = new ListView<>();
listView.getItems().addAll(employeeMap.values());

employeeMap.addListener((Change change) -> {
    if (change.wasAdded()) {
        listView.getItems().add(change.getValueAdded());
    } else if (change.wasRemoved()) {
        listView.getItems().remove(change.getValueRemoved());
    }
});

Note now that you must only modify the ObservableMap on the FX Application Thread. If you need to modify it on a different thread, you need to wrap the calls to listView.getItems().add(...) and listView.getItems().remove(...) in a Platform.runLater(...)

Upvotes: 1

Related Questions