在我的JavaFX应用程序中,我使用TreeView . 单个TreeItems包含一个图像 . 不幸的是,图像只显示一次 .
加载图像的代码如下所示 . 每次TreeView更改时都会调用它 . Image
缓存在 Map
("icons")中 . 因此,每次都会创建一个新的 ImageView
.
public final ImageView getImage(final String imageConstant) {
final Image img;
if (icons.containsKey(imageConstant)) {
img = icons.get(imageConstant);
}
else {
if (isRunFromJAR) {
img = new Image("/path/" + imageConstant, iconSizeWidth,
iconSizeHeight, false, false);
}
else {
img = new Image(getClass().getResourceAsStream(imageConstant), iconSizeWidth,
iconSizeHeight, false, false);
}
icons.put(imageConstant, img);
}
return new ImageView(img);
在 TreeCell
的 updateItem
方法中,上面返回的 ImageView
存储在名为 icon
的字段中 . 该字段在以下代码中使用,也来自 updateItem
:
if (icon == null) {
setGraphic(label);
}
else {
final HBox hbox = new HBox(ICON_SPACING);
final Label iconLabel = new Label("", icon);
hbox.getChildren().addAll(iconLabel, label);
setGraphic(hbox);
}
但由于某种原因,gif中出现的问题出现了 .
更新
实际上,ImageViews是在内部缓存的,这导致了重复数据删除 . 使用多个ImageView是解决方案 .
1 回答
ImageView 是Node的类型 . 一个节点一次只能有 one parent !
所以不要存储/缓存ImageView(-Node) . 创建新的ImageView节点 .
Edit:
正如James_D的评论所指出的那样: