javafx:如何将mousepressed事件应用于循环中的ImageView?

时间:2018-09-21 08:15:46

标签: java javafx fxml

我已经创建了一个foreach循环,该循环创建ImageView并使用javafx显示它们,但是将找到的每个ImageView必须具有赋予它的mousepressed事件,我已经编写了一个方法,我所需要知道的是将其应用到鼠标按下的Imageview上,我有点不知道如何应用它。

循环代码

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);

}

1 个答案:

答案 0 :(得分:3)

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