Prefill ListView in an application with FXML

I have a JavaFX application using FXML to create my own GUI.

When this application is running, I need to have a ListView that has some values ​​loaded, for example, from the database. So how can I do this?

I know how to make an application that loads items into a ListView after a user clicks a button or something like this (onAction attribute in FXML). But this does not suit me, since I need the elements to be loaded automatically in the ListView.

+6
source share
2 answers

If you have fxml with a controller, for example the following:

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

you can simply 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)); } } 
+8
source

This fills my sample with five predefined bit rates. I assume that if you try to add items from your controller, the list will only show these values ​​(unchecked).

 <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 operation in your FXML:

 <?import javafx.collections.*?> 
+15
source

Source: https://habr.com/ru/post/910724/


All Articles