简体   繁体   English

JavaFX ListView中的图像

[英]Image in JavaFX ListView

Is there anyway to add an image to a JavaFX ListView? 无论如何将图像添加到JavaFX ListView?

This is how I am currently setting the list view items. 这就是我当前设置列表视图项的方式。

private ListView<String> friends;
private ObservableList<String> items;
items = FXCollections.observableArrayList(getFriends);
friends.setItems(items);

I'm also using the list view value as an id to know which was selected. 我也使用列表视图值作为id来知道哪个被选中。

Implement a ListCell that displays the image and set a cellFactory on the ListView . 实现一个ListCell ,它显示图像并在ListView上设置一个cellFactory The standard oracle tutorial has an example of a custom list cell implementation. 标准的oracle教程有一个自定义列表单元格实现的示例。

You would do something along the following lines: 您可以按以下方式执行操作:

friends.setCellFactory(listView -> new ListCell<String>() {
    private ImageView imageView = new ImageView();
    @Override
    public void updateItem(String friend, boolean empty) {
        super.updateItem(friend, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            Image image = getImageForFriend(friend);
            imageView.setImage(image);
            setText(friend);
            setGraphic(imageView);
        }
    }
});

The updateItem(...) method can be called quite often, so it is probably better to preload the images and make them available to the cell, rather than creating them every time updateItem(...) is called. updateItem(...)方法可以经常调用,因此最好预先加载图像并使它们可用于单元格,而不是每次updateItem(...)都创建它们。

remember to refresh or load your Listview with myListViewWithPath.setItems(myObserverFilledWithImages); 记得使用myListViewWithPath.setItems(myObserverFilledWithImages)刷新或加载Listview ;

@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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM