Question

To put it simply: why doesn't the following small example show a light gray background on the third item in the tree control?

The code creates a JTree, populates it with three strings (directly passed in to the constructor) and overrides the getCellRenderer() method to return an instance of the custom MyTreeCellRenderer class, which has a hard-coded check to set the background color of any cell on row 2 to light gray. But when run, all cells just have the regular (white) background color.

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

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeCellRenderer;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {

    public MainFrame() {
        final MyTreeCellRenderer treeRenderer = new MyTreeCellRenderer();
        JTree tree = new JTree(new Object[] { "First", "Second", "Third" }) {
            @Override
            public TreeCellRenderer getCellRenderer() {
                return treeRenderer;
            }
        };
        tree.setRootVisible(false);

        add(tree);

        setSize(400, 300);
        setVisible(true);
    }

    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component c = super.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, hasFocus);
            if (row == 2) {
                c.setBackground(Color.LIGHT_GRAY);
            } else {
                c.setBackground(Color.WHITE);
            }
            return c;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MainFrame();
            }
        });
    }

}
Was it helpful?

Solution

DefaultTreeCellRenderer, a subclass of JLabel, must be opaque for the color to show.

image

JComponent c = (JComponent) super.getTreeCellRendererComponent(tree,
    value,isSelected, expanded, leaf, row, hasFocus);
c.setOpaque(true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top