Search code examples
javajavafxfxml

javafx: how to apply mousepressed event to ImageView(s) that is in a loop?


I've created a foreach loop that creates ImageView and displays them using javafx, but each ImageView that will be found must have like a mousepressed event given to it, I've already written a method, all i need to know is to apply it to the mousepressed Imageview and I kind a don't know how to apply it.

code for looping

private void setUpMovieContent() {
    WebResponse response = RequestVideoFromServer.getAllList();
    for (int i = 0; i < response.getMovies().length; i++) {
        String imageUrl = response.getBaseURL() + response.getMovies()[i].getImageUrl();
        Image img = new Image(imageUrl);
        ImageView imgView = new ImageView(img);
        imgView.setFitHeight(350);
        imgView.setFitWidth(230);

        Label lblTitle = new Label();
        lblTitle.setText(response.getMovies()[i].getTitle());
        lblTitle.setFont(Font.font(null,FontWeight.EXTRA_BOLD,20));
        lblTitle.setStyle("-fx-font-size: 18px;");
        lblTitle.setLayoutY(11);
        lblTitle.setLayoutX(20);

        VBox vb = new VBox();
        vb.setLayoutX(5);
        vb.setSpacing(5);
        vb.getChildren().addAll(imgView, lblTitle);

        hBox.getChildren().add(vb);
    }
    sp.setContent(hBox);
    sp.setPrefSize(600,300);
    sp.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
    sp.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
    stackPane.getChildren().add(sp);

}

Solution

  • imgView.setOnMousePressed(event -> {
        // process click
    });