简体   繁体   中英

JTree - how to setBackground to node

I read a lot of tutorials but no it helps me. I have jTree which works and setForeground works perfectly but when I want to setBackground so jTree is without changes. Can you help me how it should be write. Thanks.

import java.awt.Color;
import java.awt.Component;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;


public class UrlNodeRenderer extends DefaultTreeCellRenderer {

    public static Icon  icon    =  null;

    public UrlNodeRenderer() {
        icon = new ImageIcon(getClass().getResource("icon.png"));
    }

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

        setOpenIcon(icon);
        setClosedIcon(icon);
        setLeafIcon(icon);

        UrlTreeNode node = (UrlTreeNode) (((DefaultMutableTreeNode) value).getUserObject());
        if(node.isContainsPhrase()) {
            setForeground(Color.BLUE);
            setBackground(Color.PINK); // doesn't works
        }

        return this;
    }
}

You need to use setOpaque(true); on your TreeCellRenderer to change background color. You can add it to constructor:

public UrlNodeRenderer() {
    icon = new ImageIcon(getClass().getResource("icon.png"));
    setOpaque(true);
}

在此处输入图片说明

EDIT: You need to change background color in false and true cases like next:

 private class Renderer extends DefaultTreeCellRenderer{

        public  Renderer() {
            setOpaque(true);
        }
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean selected, boolean expanded, boolean leaf, int row,
                boolean hasFocus) {

            super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
            setBackground(selected ? Color.LIGHT_GRAY : 
                (leaf ? Color.GRAY : tree.getBackground()));
            return this;
        }

    }

In your case:

if(node.isContainsPhrase()) {
        setForeground(Color.BLUE);
        setBackground(Color.PINK); // doesn't works
}

you set color to all nodes, because you never set color for false case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM