Felix Felix - 3 months ago 20
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>() {

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

System.out.println(observable.getValue());
}
});

Answer

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;
     }

    @Override
    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.setItems(FXCollections.observableArrayList(1,2,3,4,5,6));
boxValidPwd.getSelectionModel().selectedIndexProperty().addListener(new MyChangeListener(boxValidPwd));

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