boycod3 boycod3 - 5 months ago 31
Java Question

Values not showing on JavaFX combo box

I have this code below, for populating values on the JavaFX

ComboBox
.

The System.out inside is printing state name inside for each loop, but the state name is not showing on the combo box.

@FXML private ComboBox<String> cmboState = new ComboBox<String>();

ObservableList<String> stateList = FXCollections.observableArrayList();

stateList.clear();
stateService = (StateService) App.getAppContext().getBean("StateService");
List<State> states = stateService.findAllState();
cmboState.setItems(stateList);
for (State state : states) {
System.out.println(state.getStateName());
stateList.add(state.getStateName());
}
stateList.add(0, "Select one");
cmboState.setItems(stateList);

Answer

There is no actual problem with this snippet, it is working, so please make sure that stateList is not erased somewhere else in your code.

Also, calling cmboState.setItems(stateList); twice is useless, as it is an ObservableList:

cmboState.setItems(stateList); // Here stateList is empty
for (int i = 0; i<3; i++) {            
    stateList.add("aaa" + i);
}
stateList.add(0, "Select one");

So my best guess is that you erase this list somewhere else, therefore the list of items in your ComboBox will be also erased.