I am making an application using only Java and FXML for a school project. I am not allowed to use scene builder. In the appplication, the user enters their info into a form. This info is then used to create an instance of one of three possible classes. One of form's fields is 'Nationality', hence I would like to use a dropdown containing countries for them to pick from. I created a ComboBox in my Main.java class (it was initally in my controller) with the help of MBec's answer to this question: link.
My question is: How do I access the ComboBox I made in Main.java from within my FXML file and display it on my existing scene? I currently have a placeholder ComboBox in there but it is not populated.
Populated ComboBox from Main.java:
ObservableList<String> all_countries = Stream.of(Locale.getISOCountries())
.map(locales -> new Locale("", locales))
.map(Locale::getDisplayCountry)
.collect(Collectors.toCollection(FXCollections::observableArrayList));
final ComboBox<String> country_list = new ComboBox<>(all_countries);
I tried setting an onAction property on an empty ComboBox made in FXML with a method that created and then returned the populated ComboBox from Main.java but as expected this did not work.
I did manage to verify that the ComboBox works by setting it as the root of a new Scene. This was just to ensure myself that the ComboBox itself wasn't the cause of the issue. New scene used to test:
I also tried tried making the ComboBox a different way (see Keyuri Bhanderi's answer here: link), however this also did not work.
Code for my existing scene:
Parent root = FXMLLoader.load(getClass().getResource("view/sample.fxml"));
primaryStage.setTitle("form");
primaryStage.setScene(new Scene(root, 600, 600));
I was expecting to be able to access the ComboBox 'country_list' from within sample.fxml and display it on my existing scene, hence that is my aim. I am new to Java and FXML so the answer may be obvious but I have been stuck on this for a day or two. Apologies for any bad formatting; this is my first time using SO. If anyone has time to spare I also have an additional question. Is getISOCountries(), the best Locale method to use when asking for nationality? I noticed it had a lot more options than forms tend to do when asking for nationality / country, and it also was not completely in alphabetical order. Thank you all in advance.
I managed to figure it out after browsing some other SO questions regarding similar problems. I made a HBox inside my FXML like so:
<HBox
id="country_container"
fx:id="country_container"
GridPane.columnIndex="1"
GridPane.rowIndex="12"
/>
It is simply there to act as a container for the ComboBox. I then did the following in my Controller's Initialize method:
countries_combo();
combo_box.getChildren().add(country_list);
The first line calls a method which creates and returns the ComboBox and the second adds it as a child to the manually-created HBox.