Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 422
Victoria Agafonova Avatar asked Mar 14 '12 15:03

Victoria Agafonova


People also ask

What is FXML used for?

FXML is an XML-based user interface markup language created by Oracle Corporation for defining the user interface of a JavaFX application. FXML presents an alternative to designing user interfaces using procedural code, and allows for abstracting program design from program logic.

Is FXML a markup language?

Overview. FXML is a scriptable, XML-based markup language for constructing Java object graphs.


2 Answers

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.*?>
like image 53
Andreas Avatar answered Oct 13 '22 18:10

Andreas


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));

    }
}
like image 31
Sergey Grinev Avatar answered Oct 13 '22 20:10

Sergey Grinev