JavaFX / how to load/populate values at start up?


I started working with JavaFX just today and already need some advise. I load the applicaton.fxml (created with Oracle SceneBuiler) using the FXMLLoader in the start(Stage ...) method of the MainApplication (which has an ApplicationController specified in my application.fxml file).

<AnchorPane id="AnchorPane" disable="false" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="600.0" prefWidth="800.0" styleClass="theme" xmlns:fx="" xmlns="" fx:controller="app.AppController">
...more code here...
<ComboBox id="cmb_locations" fx:id="cmb_locations">
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="Item 1" />
            <String fx:value="Item 2" />
            <String fx:value="Item 3" />

Now, I have a ComboBox in the applicaton.fxml, which has three items (the default items). What I need is to populate that ComboBox during the startup with my own values. Does anyone know how to achieve that and where to put the relevant code snippets (app.AppController or something similar)? Thanks in advance.

8/21/2013 3:11:19 PM

Accepted Answer

You have some controller for you fxml file. There you have access to your ComboBox. You could put this code to setup list of elements (probably in initialize() method):

If you don't really want to edit your fxml file you can just clear the list first with cmb_locations.getItems().clear(); before you setup new list.

public class ApplicationController implements Initializable {

    ComboBox cmb_locations;
    public void initialize(URL url, ResourceBundle rb) {
        List<String> list = new ArrayList<String>();
        list.add("Item A");
        list.add("Item B");
        list.add("Item C");
        ObservableList obList = FXCollections.observableList(list);
8/21/2013 3:46:57 PM

Start by removing the default values on the FXML "Item 1" "Item 2" ... just to have

<FXCollections fx:factory="observableArrayList">

and on your controller if you want retrieve your combobox you have to inject it by doing

ComboBox cmb_locations

public void initialize(URL url, ResourceBundle resource) {
//here populate your combobox

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow