Javafx ListView与图像而不是字符串

时间:2015-04-08 13:01:17

标签: listview javafx imageview

我正试图在我的程序中制作一个带有电影图片的横幅,但是我有麻烦将我带有图像的图片列表转换为实际图像。
我该怎么做,这是我目前的代码:

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。

3 个答案:

答案 0 :(得分:4)

使用细胞工厂。您需要使用此代码创建ListView(如果您使用的是FXML控制器,则需要initialize()方法):

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中显示图片的完整示例:

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

答案 1 :(得分:1)

James_D为您提供了非基础fxml应用程序的答案,如果您在FXM和Controlller应用程序中进行开发,请记得刷新或加载Listview 使用 myListViewWithPath.setItems(myObserverFilledWithImages);

@FXML
    private void browseButton(ActionEvent event) throws Exception {
        System.out.println("browseButton");
        DirectoryChooser chooser = new DirectoryChooser();
        File file = chooser.showDialog(myStage);
        file = new File("E:\\FOLDER\\Imagen_File");

        if (file != null) {
            directoryField.setText(file.toString());
            oImage.setAll(load(file.toPath()));
        }
        imageFilesList.setItems(oImage); //this one load or refresh the ListView
    }

答案 2 :(得分:0)

最好的答案是:

ListView<ImageView> listView = new listView();
ObservableList<ImageView> items = FXCollections.observableArrayList();
listView.setItems(items);

ListView是通用的 - 使用它。

然后使用将项目(在本例中为图像)添加到列表中:

ImageView item = new ImageView("file:myimage.png");
listView.getItems().add(item);