Say I have a controller with
@FXML private ObservableList<String> myStrings = FXCollections.observableArrayList();
Is it possible to write any FXML which will wire up a ListView with myStrings as its items?
My first try was:
<ListView>
<items fx:id="myStrings"/>
</ListView>
But this complains that fx:id is not valid in that position. I also tried
<ListView items="${controller.myStrings}"/>
...but it couldn't resolve that value.
<ListView fx:id="myStringsListView"/>
// In controller
@FXML private ListView<String> myStringsListView;
@FXML public void initialize() {
myStringsListView.setItems(myStrings);
}
This is what I am doing now but the amount of indirection and boilerplate here hurts me.
The following works
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.control.ListView?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" fx:controller="ListViewController">
<center>
<ListView items="${controller.myStrings}" />
</center>
</BorderPane>
with the following controller (the main difference, I think, being that you either didn't define an accessor method for the list, or named it incorrectly):
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class ListViewController {
private final ObservableList<String> myStrings = FXCollections.observableArrayList();
public ListViewController() {
myStrings.addAll("One", "Two", "Three");
}
public ObservableList<String> getMyStrings() {
return myStrings ;
}
}
This quick test:
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class ListViewItemsFromControllerTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setScene(new Scene(FXMLLoader.load(getClass().getResource("ListViewItemsFromController.fxml"))));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
produces

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With