3

I have three combo box: Country, state and city

How can I become a dependent on another? For example, if I select Brazil appears their states and later the cities of selected state. But if I select United States in the country will show their states

I am using MySQL as the database, if you need some configuration in the database also tell me ... It's the first time you work with it, thank you very much.

Junior
  • 31
  • 1
  • 3
  • Obs: example of how I'm populating a combobox public void country() { listCountry = countryDAO.show(); observableListCountry = FXCollections.observableArrayList(listCountry); cbxCountry.setItems(observableList); } – Junior Oct 10 '16 at 20:06
  • 1
    Please don't post code in the comments: [edit] your question and add it there. – James_D Oct 10 '16 at 20:08

1 Answers1

7

Register a listener with the country combo box and update the state combo box when the selected item changes:

cbxCountry.valueProperty().addListener((obs, oldValue, newValue) -> {
    if (newValue == null) {
        cbxState.getItems().clear();
        cbxState.setDisable(true);
    } else {
        // sample code, adapt as needed:
        List<State> states = stateDAO.getStatesForCountry(newValue);
        cbxState.getItems().setAll(states);
        cbxState.setDisable(false);
    }
});

You could also do this with bindings if you prefer:

cbxState.itemsProperty().bind(Bindings.createObjectBinding(() -> {
    Country country = cbxCountry.getValue();
    if (country == null) {
        return FXCollections.observableArrayList();
    } else {
        List<State> states = stateDAO.getStatesForCountry(country);
        return FXCollections.observableArrayList(states);
    }
},
cbxCountry.valueProperty());

(and if you want the disable functionality from the solution above also do cbxState.disableProperty().bind(cbxCountry.valueProperty().isNull());).

James_D
  • 201,275
  • 16
  • 291
  • 322