JavaFX ListView中的图像 [英] Image in 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
,显示图像并设置
。 标准oracle教程有一个自定义列表示例单元格实现。 ListView
上的> cellFactory
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屋!