Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 905
nyyrikki Avatar asked Dec 07 '22 05:12

nyyrikki


1 Answers

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);
        ...
    }
}
like image 124
Knight of Ni Avatar answered Jan 17 '23 07:01

Knight of Ni