Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX bind a controller variable to a component property

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.

Please do not post this solution:

<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.

like image 534
Dan Passaro Avatar asked Apr 17 '26 19:04

Dan Passaro


1 Answers

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

enter image description here

like image 124
James_D Avatar answered Apr 19 '26 10:04

James_D