首页 文章

JavaFX:ImageView只显示一次Image

提问于
浏览
1

在我的JavaFX应用程序中,我使用TreeView . 单个TreeItems包含一个图像 . 不幸的是,图像只显示一次 .

a gif showing the problem

加载图像的代码如下所示 . 每次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);

TreeCellupdateItem 方法中,上面返回的 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 回答

  • 4

    上面返回的ImageView存储在名为icon的字段中 . 字段用于以下代码中...

    ImageView 是Node的类型 . 一个节点一次只能有 one parent
    所以不要存储/缓存ImageView(-Node) . 创建新的ImageView节点 .

    Edit:
    正如James_D的评论所指出的那样:

    ...您可以为每个ImageView使用相同的Image(-Object)...

相关问题