Updating ImageIcon in JTree without repainting the Tree?

折月煮酒 提交于 2019-11-27 09:51:32
trashgod

Use the approach shown in TreeIconDemo2 to condition the renderer based on the model's value. For example,

private class MyRenderer extends DefaultTreeCellRenderer {

    private Icon okIcon;

    public MyRenderer(Icon okIcon) {
        this.okIcon = okIcon;
    }

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value,
        boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
        super.getTreeCellRendererComponent(
            tree, value, sel, exp, leaf, row, hasFocus);
        YourMutableTreeNode node = (YourMutableTreeNode) value;
        if (leaf && node.getStatus().equals("OK")) {
            setIcon(okIcon);
        }
        return this;
    }
}

Addendum: You can't simply invoke nodeChanged() on a new TreeNode that's not part of the tree; the new node has no parent. If you specify an existing node to nodeChanged(), the notification will happen automatically. If needed, there's an example of searching a tree here.

When you want the model to be updated, as you do here, you are correct that you want to call nodeChanged. What I think may be wrong is that you are passing in an entirely new node, which obviously doesn't match one found in the tree. Try passing in a reference to the node in the tree you modified - that way the model can find know which node you modified.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!