JavaFX ListView中的图像 [英] Image in JavaFX ListView

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

问题描述

是否有将图像添加到JavaFX ListView?

Is there anyway to add an image to a 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);

我还使用列表视图值作为id来知道选择了哪个。

I'm also using the list view value as an id to know which was selected.

推荐答案

实施 ListCell ,显示图像并设置 ListView 上的> cellFactory 标准oracle教程有一个自定义列表示例单元格实现。

Implement a ListCell that displays the image and set a cellFactory on the ListView. The standard oracle tutorial has an example of a custom list cell implementation.

您可以按以下方式执行操作:

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

updateItem(...)方法可以经常调用,因此最好预加载图像并使它们可用于单元格,而不是每次调用 updateItem(...)时创建它们。

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.

这篇关于JavaFX ListView中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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