组合框依赖于另一个组合框 - JavaFX

Jun*_*ior 2 java mysql combobox javafx

我有三个组合框:国家、州和城市

我怎么可能成为另一个人的依赖者?例如,如果我选择巴西,则会出现他们的州,然后是所选州的城市。但是如果我在国内选择美国会显示他们的州

我用的是mysql作为数据库,如果你需要在数据库中进行一些配置也告诉我......这是你第一次使用它,非常感谢。

Jam*_*s_D 5

向国家组合框注册一个监听器,并在所选项目发生变化时更新状态组合框:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

如果您愿意,也可以使用绑定来执行此操作:

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());
Run Code Online (Sandbox Code Playgroud)

(如果您想要上述解决方案中的禁用功能,也可以这样做cbxState.disableProperty().bind(cbxCountry.valueProperty().isNull());)。