Populate Choicebox defined in FXML

血红的双手。 提交于 2019-11-28 12:40:38

How to fix it

Remove the line countChoiceBox = new ChoiceBox(); and everything will work fine, assuming you have no other bugs elsewhere in your application.

The program will use the reference to the countChoiceBox which is part of the node hierarchy created by the FXMLLoader and set in your scene.

What is happening

Loading a new FXML in onChangeCountClick will:

  1. Create a new supermarket.ManageWindowCC controller.
  2. Create a hierarchy of Nodes based upon the FXML definition.
  3. One of the nodes in the hierarchy will be a ChoiceBox.
  4. The ChoiceBox which the FXML loader automatically creates for you will be assigned to the countChoiceBox member.
  5. You then take the hierarchy of nodes assigned to root and add it to your new Scene on your new Stage.

So, after you load the FXML, countChoiceBox is initialized to an empty ChoiceBox instantiated by your FXMLLoader

This is all fine so far . . .

What you then do is (incorrectly) write:

countChoiceBox = new ChoiceBox();

The rule of thumb you violate is => never use new to create a assign a value to a members tagged @FXML.


Also see the somewhat related example for populating a ComboBox using FXML (though that sample uses a ComboBox and populates its data directly in FXML, so it is not directly applicable to your situation).

@using FXML STEP 1: Add a choice box in the scene builder and call it maybe(choiceBox) STEP 2: IN the controller add the following codes @FXML private ChoiceBox choiceBox ;

@Override
public void initialize(URL url, ResourceBundle rb) {
 ObservableList<String> list = FXCollections.observableArrayList();
   list.addAll("choice1", "choice2","choice3");
  //populate the Choicebox;  
  choiceBox .setItems(list);

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!