0

If item in the first combo box is selected then I want to be able to populate the second combo box with the associated items

   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"));

  }       
fabian
  • 80,457
  • 12
  • 86
  • 114
  • Note: You should take a look at [How do I compare strings in Java?](https://stackoverflow.com/q/513832/8097737). –  Apr 11 '18 at 08:18

2 Answers2

1

You need to do this when the value changes instead of using the value initially assigned (null).

Furthermore you should not compare strings using == and the call to toString can be avoided by using a type parameter for ChoiceBox.

Also it's preferable to use a Map<String, ObservableList<String>> instead of doing a if/else if or using a switch:

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);
});
fabian
  • 80,457
  • 12
  • 86
  • 114
0

Since you want to do something when the selected item in the ChoiceBox is change you need to add a 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"));
        }
    }
);