Adding and modifying a List of Strings in a JavaFx ListView is a relatively easy task, although may not be completely intuitive at first glance. In order to have changes to a List automatically reflected in a ListView you will need to make use of the ListProperty class, however setting items in the property is not as easy as calling the add() or addAll() methods. This is because the underlying ObservableList class that the Property is using does not support the add() or addAll() methods. Instead, you will need to first wrap your List in an ObservableList, and then pass that ObservableList to the ListProperty instance.
Below is an small sample application which illustrates this point. There are two ArrayLists which contain Strings of data. One contains the currency codes of some Asian currencies, and the other contains the currency codes of European currencies. The list should initially be loaded with the Asian currencies, and when the user clicks on the Button, the handleButtonAction() method is invoked, which will cause the European currency list to be rendered in the ListView.
First, the FXML layout for the UI.
Next, the controller class for the application
The two lists are populated within the initialize() method of the controller. As you can see it is not possible simply to call the addAll() method on the ListProperty, as it will result in an “OperationNotSupportedException”. Instead, at line 57, the FXCollections class is used to wrap the ArrayList in an ObservableArrayList instance, which is then passed into the ListProperty.
Finally, in the handleButtonAction() method, the europeanCurrencyList is wrapped in ObservableList, and passed to the ListProperty. Since the ListProperty and the ListView are bound together (at line 53), the ListView is automatically updated with the European currency values.
Below are screenshots of the sample app both before and after the button has been clicked.