Question

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.

Was it helpful?

Solution

If you have fxml with Controller, like next:

<AnchorPane xmlns:fx="http://javafx.com/fxml" fx:controller="test.Sample">
    <children>
        <ListView fx:id="listView"/>
    </children>
</AnchorPane>

you can just implement Initializable in your Controller:

public class Sample implements Initializable {
    @FXML
    private ListView listView;

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

        listView.setItems(FXCollections.observableList(values));

    }
}

OTHER TIPS

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">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="4800" />
            <String fx:value="9600" />
            <String fx:value="19200" />
            <String fx:value="57600" />
            <String fx:value="115200" />
        </FXCollections>
    </items>
</ChoiceBox>

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 StackOverflow
scroll top