根据自定义对象状态更改JTree图标

时间:2014-08-29 11:33:00

标签: java swing jtree treecellrenderer

我有一个JTree,基于几个自定义类。我想给几个节点一个特定的图标。因此,我根据此链接执行了以下代码:Dynamically change icon of specific nodes in JTree

        DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer() {
        private static final long serialVersionUID = 1L;
        private Icon good = new ImageIcon(getClass().getResource("/good.png"));
        private Icon dunno = new ImageIcon(getClass().getResource("/dunno.png"));
        private Icon bad = new ImageIcon(getClass().getResource("/bad.png"));

        @Override
        public Component getTreeCellRendererComponent(JTree tree,
            Object value, boolean selected, boolean expanded,
            boolean isLeaf, int row, boolean focused) {

            Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused);

            // JTreePanelNode node = (JTreePanelNode)c; - not possible
            return c;
        }
    };
    this.getTree().setCellRenderer(renderer);   

我的每个节点都是JTreePanelNode(自定义类)的对象,它保存了一个特定的状态,可以通过setState(String s)设置并通过getState()获取。所以我想要的是这样的事情:

if(node.getState().equals("good")) ..
else if(node.getState.equals("bad")) ..
else ..

我怎样才能实现这样的目标?根据我的理解,渲染器使用getTreeCellRendererComponent遍历每个节点并应用一个特定的图标,我可以使用setIcon和几个ifs()来选择。但是我无法转换为JTreePanelNode。有解决方案吗谢谢:))

2 个答案:

答案 0 :(得分:4)

全部取决于您的JTreePanelNode类。如果它实现了TreeNode接口,你可以选择:

public Component getTreeCellRendererComponent(JTree tree, Object value,
        boolean sel, boolean expanded, boolean leaf, int row,
        boolean hasFocus) {
    Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf,
            row, hasFocus);
    TreeNode current = (TreeNode)value;

    if (leaf) {
        //set leaf icon
    } else if (expanded) {
        //set expanded icon
    } else {
        // set default state
    }

    if (hasFocus)
        //set what it looks like if focused

    else if (selected)
        //set what it looks like if selected

    else
        //set default l&f

    comp.setIcon(whatevericonset in above conditions);

    return comp;
}

当然,您可以添加更多状态,具体取决于您的节点class.getState()。

答案 1 :(得分:2)

您可以访问该树中表示的Object:

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean isLeaf, int row, boolean focused) {

    Component c = super.getTreeCellRendererComponent(tree, value, selected, expanded, isLeaf, row, focused);
    DefaultMutableTreeNode node = (DefaultMutableTreeNode ) value;
    Object representedObject = node.getUserObject();

    JLabel superLabel = super.getTreeCellRendererComponent();
    String text = label.getText();

    if(object.isGood() ){ //i don't know your code
        superLabel .setText (text +"goooooooood");
    }else{
        superLabel .setText (text +"badbadbabd");
    }
    return superLabel ;
}