dogplasma
dogplasma

Reputation: 5

Dynamically fill ListView from data model in javafx

I've created a method to fill listviews with objects that fit the correct criteria:

public void setCourseModules(Collection<Module> modules) {

    t1UnSel.getItems().clear();
    t2UnSel.getItems().clear();
    t1Sel.getItems().clear();
    t2Sel.getItems().clear();
    yrSel.getItems().clear();

    modules.forEach(m -> {
        if (m.getRunPlan().equals(Delivery.TERM_1)) {
            if (m.isMandatory()) {
                t1Sel.getItems().add(m);
            } else {
                t1UnSel.getItems().add(m);
            }
        } else if (m.getRunPlan().equals(Delivery.TERM_2)) {
            if (m.isMandatory()) {
                t2Sel.getItems().add(m);
            } else {
                t2UnSel.getItems().add(m);
            }
        } else {
            yrSel.getItems().add(m);
        }
    });
}

and call it with:

smp.setCourseModules(course[0].getModulesOnCourse());

However, this is just a hardcoded entry to get the first course from the Array, I need to be able to dynamically change that index based on a comboBox selection, struggling to think how I can get the index of the course name as an int without hardcoding it...

Attached is the gist, the Student Setup class and the Controller are most important, Student class containing the comboBox and Controller has the course data declaration.

Upvotes: 0

Views: 274

Answers (2)

Martin P
Martin P

Reputation: 114

Just to extend M. le Rutte's answer

You could use

myComboBox.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
    @Override
    public void changed(ObservableValue observable, Object oldValue, Object newValue) {
        //do something with selected item
    }
});

or

myComboBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
    @Override
    public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
        //do something with selected index
    }
});

Upvotes: 1

M. le Rutte
M. le Rutte

Reputation: 3563

My take on your question is that you need to get the selected combobox value. ComboBox has a value property:

public ObjectProperty<T> valueProperty();

The value of this ComboBox is defined as the selected item if the input is not editable, or if it is editable, the most recent user action: either the value input by the user, or the last selected item.

Upvotes: 0

Related Questions