Felix Felix - 1 year ago 185
Java Question

Using ChangeListener for JavaFX ChoiceBox working with the String

When using a ChangeListener added to a ChoiceBox, is there a way to access the items from the observableArrayList directly, to update for example a String type Instance variable?

I implemented this code here, which lets me work fine, with the index values of the observableArrayList. But, I am pretty new to Java so I am just wondering if that is the way to go? Or if there is a better way to update the String Instance variable with the ChangeListener.

cb_1.setItems(FXCollections.observableArrayList("High", "Average ", "Low"));
cb_1.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {

public void changed(ObservableValue<? extends Number> observable,
Number oldVal, Number newVal) {


Answer Source

I had the same problem. I solved by creating a class that implements ChangeListener, but with a ChoiceBox final field that is set in the class constructor

private class MyChangeListener implements ChangeListener<Number>{
    final ChoiceBox<Number> cb;

    MyChangeListener(ChoiceBox<Number> cb) {
        this.cb = cb;

    public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
        System.out.println("cb: "+cb.getId());


I used it later in the code like

@FXML   ChoiceBox boxValidPwd;
boxValidPwd.getSelectionModel().selectedIndexProperty().addListener(new MyChangeListener(boxValidPwd));

and you shoud see in the output the choiceBox ID used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download