在JTree中更新ImageIcon而不重新绘制树吗? [英] Updating ImageIcon in JTree without repainting the Tree?

查看:93
本文介绍了在JTree中更新ImageIcon而不重新绘制树吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我在DefaultTreeNode()UserObject()中编辑属性private string status="OK".

Basically I edit an attribute private string status="OK" in the UserObject() of a DefaultTreeNode().

我有一个CustomRenderer,它的implements DefaultCellRenderer通过呈现TreeNodeUserObject的"OK"属性来设置图标.

I have a CustomRenderer which implements DefaultCellRenderer, which sets the Icon by rendering the "OK" attribute of UserObject of a TreeNode.

最初,当我选择一个节点时,图标会更改.我正在使用Tree.revalidate()& Tree.repaint(),并且更改已得到体现.

Originally, when I select a node, the icon changes. I am using Tree.revalidate() & Tree.repaint(), and the change is being reflected.

但是,我不确定这是否非常有效.这样做的正确方法是什么?我尝试执行TreeModel.nodesChanged(new DefaultMutableTreeNode(myUserObject)),但TreeNodeChanged event不会触发.

However, I am not sure if this very efficient. What would be the proper way of doing this? I tried doing TreeModel.nodesChanged(new DefaultMutableTreeNode(myUserObject)) but the TreeNodeChanged event will not fire.

那么,每次TreeNode的用户对象更改以查看图形更新时,我是否坚持使用重绘整个树?

So am I stuck to using repainting the entire tree everytime a userboject of a TreeNode is changed to see the graphic update?

推荐答案

使用

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.

这篇关于在JTree中更新ImageIcon而不重新绘制树吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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