Larry
Larry

Reputation: 101

Filling ListView from fxml file in JavaFX, empty listview

Hello i starting my adventure with javafx, i use SceneBuilder to make theme, this is my XmlFile:http://pastebin.com/9fvhREKc controller:

public class Controller {

@FXML
private ListView templates;
@FXML
private ImageView image;

@FXML
void initalize() {
    ObservableList elements = FXCollections.observableArrayList();
    elements.add("first");
    elements.add("second");
    elements.add("third");
    image.setImage(new Image("file:test.jpg"));
    templates.setItems(elements);
}

} and my main class

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(this.getClass().getResource("Sample.fxml"));
    Controller controller = new Controller();
    loader.setController(controller);
    Pane root = loader.load();
    Scene scene = new Scene(root);
    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
}

} and when i start application my theme work but list and image is empty;/

Upvotes: 0

Views: 1100

Answers (1)

James_D
James_D

Reputation: 209714

You need to set the controller before you load the FXML, since the controller's initialize method is invoked as part of the load() process:

FXMLLoader loader = new FXMLLoader();
loader.setLocation(this.getClass().getResource("Sample.fxml"));
Controller controller = new Controller();
loader.setController(controller);
Pane root = loader.load();
Scene scene = new Scene(root);

Also note you have a typo in your Controller class: the method name initialize is misspelled. Since the FXMLLoader uses reflection to find and execute this method, this will prevent the method from being executed:

public class Controller {

    @FXML
    private ListView templates;
    @FXML
    private ImageView image;

    @FXML
    // void initalize() {
    void initialize() {
        ObservableList elements = FXCollections.observableArrayList();
        elements.add("first");
        elements.add("second");
        elements.add("third");
        image.setImage(new Image("file:test.jpg"));
        templates.setItems(elements);
    }

} 

Upvotes: 1

Related Questions