带有图像而不是字符串的 Javafx ListView [英] Javafx ListView with Images instead of Strings

查看:21
本文介绍了带有图像而不是字符串的 Javafx ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的程序中制作带有电影图片的横幅,但我无法将带有图像网址的列表转换为实际图像.
我该怎么做,这是我当前的代码:

I am trying to make a banner in my programm with movie pictures, but I'm having troubles to turn the List I have with the urls of images to actual Images.
How can I do this, here is my current code:

public void initData(boolean onlineProvider, String uritext) {
        op = Providers.createTestProvider();
        List<Movie> films = (List<Movie>) op.getMovieDAO().listFiltered();
        ObservableList<String> posters = FXCollections.observableArrayList();
        for( Movie movie : films){
            String poster = movie.getPoster();
            posters.add(poster);

        }
        banner.setOrientation(Orientation.HORIZONTAL);
        banner.setItems(posters);

    }
}

明确地说,banner 是一个 ListView.

To be clear, banner is a ListView.

推荐答案

使用单元工厂.您需要在创建 ListView 的地方使用此代码(如果您在 FXML 控制器中,则在 initialize() 方法中):

Use a cell factory. You need this code where you create the ListView (or in the initialize() method if you are in an FXML controller):

banner.setCellFactory(listView -> new ListCell<String>() {
    private ImageView imageView = new ImageView();

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setGraphic(null);
        } else {
            // true makes this load in background
            // see other constructors if you want to control the size, etc
            Image image = new Image(item, true) ; 
            imageView.setImage(image);
            setGraphic(imageView);
        }
    }
});

这是一个在 ListView 中显示图像的完整示例:

Here is a complete example which displays images in a ListView:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

public class ListViewImageBrowser extends Application {

    @Override
    public void start(Stage primaryStage) {
        ObservableList<Path> imageFiles = FXCollections.observableArrayList();

        TextField directoryField = new TextField();
        Button browseButton = new Button("Browse");
        Button loadButton = new Button("Load");

        EventHandler<ActionEvent> loadHandler = event -> imageFiles.setAll(load(Paths.get(directoryField.getText())));
        loadButton.setOnAction(loadHandler);
        directoryField.setOnAction(loadHandler);

        browseButton.setOnAction(event -> {
            DirectoryChooser chooser = new DirectoryChooser();
            File file = chooser.showDialog(primaryStage);
            if (file != null) {
                directoryField.setText(file.toString());
                imageFiles.setAll(load(file.toPath()));
            }
        });

        HBox controls = new HBox(5, directoryField, browseButton, loadButton);
        controls.setAlignment(Pos.CENTER);
        controls.setPadding(new Insets(5));

        ListView<Path> imageFilesList = new ListView<>(imageFiles);
        imageFilesList.setCellFactory(listView -> new ListCell<Path>() {
            private final ImageView imageView = new ImageView();

           @Override
            public void updateItem(Path path, boolean empty) {
                super.updateItem(path, empty);
                if (empty) {
                    setText(null);
                    setGraphic(null);
                } else {
                    setText(path.getFileName().toString());
                    imageView.setImage(new Image(path.toUri().toString(), 80, 160, true, true, true));
                    setGraphic(imageView);
                }
            }
        });


        ImageView imageView = new ImageView();
        imageFilesList.getSelectionModel().selectedItemProperty().addListener((obs, oldFile, newFile) -> {
            if (newFile == null) {
                imageView.setImage(null);
            } else {
                imageView.setImage(new Image(newFile.toUri().toString(), true));
            }
        });
        imageFilesList.setMinWidth(200);

        StackPane imageHolder = new StackPane(imageView);
        imageView.fitWidthProperty().bind(imageHolder.widthProperty());
        imageView.fitHeightProperty().bind(imageHolder.heightProperty());
        imageView.setPreserveRatio(true);

        BorderPane root = new BorderPane(imageHolder, controls, null, null, imageFilesList);

        Scene scene = new Scene(root, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private List<Path> load(Path directory) {
        List<Path> files = new ArrayList<>();
        try {
            Files.newDirectoryStream(directory, "*.{jpg,jpeg,png,JPG,JPEG,PNG}").forEach(file -> files.add(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return files ;
    }

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

这篇关于带有图像而不是字符串的 Javafx ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆