nyyrikki
nyyrikki

Reputation: 1486

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="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="app.AppController">
...more code here...
<ComboBox id="cmb_locations" fx:id="cmb_locations">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="Item 1" />
            <String fx:value="Item 2" />
            <String fx:value="Item 3" />
        </FXCollections>
    </items>
</ComboBox>

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.

Upvotes: 4

Views: 18904

Answers (3)

Knight of Ni
Knight of Ni

Reputation: 1830

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 {

    @FXML
    ComboBox cmb_locations;
    ...
    @Override
    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);
        cmb_locations.getItems().clear();
        cmb_locations.setItems(obList);
        ...
    }
}

Upvotes: 8

agonist_
agonist_

Reputation: 5032

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

<FXCollections fx:factory="observableArrayList">
    </FXCollections>

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

@FXML
ComboBox cmb_locations

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

Upvotes: 4

Ekans
Ekans

Reputation: 1067

In your controller, you implement the Initializable interface. Then in initialize method, you just add your code to load your combo box.

Upvotes: 3

Related Questions