Prefill ListView in an application with FXML


I have JavaFX application using FXML to build its GUI.

When this application is launched, I need to have ListView, which has some values loaded, for example, from database. So, how can I do this?

I know how to make application, which loads items to ListView after user clicks a button, or something like this ("onAction" attribute in FXML). But this does not suites me as I need items to be loaded automaticaly to the ListView.

3/15/2012 7:03:23 PM

Accepted Answer

If you have fxml with Controller, like next:

<AnchorPane xmlns:fx="" fx:controller="test.Sample">
        <ListView fx:id="listView"/>

you can just implement Initializable in your Controller:

public class Sample implements Initializable {
    private ListView listView;

    public void initialize(URL url, ResourceBundle rb) {
        // change next line to DB load
        List<String> values = Arrays.asList("one", "two", "three");


3/15/2012 6:59:24 PM

This fills my choicebox with the five predetermined baud rates. I assume if you try to add items from your controller, the list only shows those values (untested).

<ChoiceBox fx:id="baudRates" layoutX="234.0" layoutY="72.0">
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="4800" />
            <String fx:value="9600" />
            <String fx:value="19200" />
            <String fx:value="57600" />
            <String fx:value="115200" />

You also need to include the following import statement in your FXML:

<?import javafx.collections.*?>

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