Javafx 没有错误,但if语句没有按预期的方式运行。我也不确定if语句应该放在哪里
如果选择了第一个组合框中的项目,那么我希望能够用关联的项目填充第二个组合框Javafx 没有错误,但if语句没有按预期的方式运行。我也不确定if语句应该放在哪里,javafx,Javafx,如果选择了第一个组合框中的项目,那么我希望能够用关联的项目填充第二个组合框 ChoiceBox cbDestination = new ChoiceBox(FXCollections.observableArrayList( "Krakow", "Ios", "Amsterdam")); ChoiceBox cbAccommodation = new ChoiceBox(); if (cbDesti
ChoiceBox cbDestination = new ChoiceBox(FXCollections.observableArrayList(
"Krakow",
"Ios",
"Amsterdam"));
ChoiceBox cbAccommodation = new ChoiceBox();
if (cbDestination.getValue().ToString() == "Krakow" ) {
cbAccommodation.setItems(FXCollections.observableArrayList(
"Your Place",
"Flames"));
} else if (cbDestination.getValue().ToString() == "Ios" ) {
cbAccommodation.setItems(FXCollections.observableArrayList(
"Homers",
"Marias"));
} else {
cbAccommodation.setItems(FXCollections.observableArrayList(
"Old Quarter",
"St.Christophers Inn"));
}
由于要在ChoiceBox中的选定项为change时执行某些操作,因此需要添加ChangeListener:
cbDestination.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if ("Krakow".equals(newValue)) {
cbAccommodation.setItems(FXCollections.observableArrayList("Your Place", "Flames"));
} else if ("Ios".equals(newValue)) {
cbAccommodation.setItems(FXCollections.observableArrayList("Homers", "Marias"));
} else {
cbAccommodation.setItems(FXCollections.observableArrayList("Old Quarter", "St.Christophers Inn"));
}
}
);
当值更改时,您需要执行此操作,而不是使用最初指定为null的值 此外,您不应该使用==来比较字符串,可以通过使用ChoiceBox的类型参数来避免对toString的调用 此外,最好使用映射,而不是执行if/else if或使用开关:
注意:你应该看看。非常感谢你,真的很有帮助!
ChoiceBox<String> cbDestination = new ChoiceBox<>(FXCollections.observableArrayList(
"Krakow",
"Ios",
"Amsterdam"));
ChoiceBox<String> cbAccommodation = new ChoiceBox<>();
Map<String, ObservableList<String>> values = new HashMap<>();
values.put("Krakow", FXCollections.observableArrayList("Your Place", "Flames"));
values.put("Ios", FXCollections.observableArrayList("Homers", "Marias"));
values.put("Amsterdam", FXCollections.observableArrayList("Old Quarter", "St.Christophers Inn"));
cbDestination.valueProperty().addListener((o, oldVal, newVal) -> {
ObservableList<String> items = values.get(newVal);
cbAccommodation.setItems(items == null ? FXCollections.emptyObservableList() : items);
});