调用自定义CellRenderer但似乎没有效果

时间:2013-05-03 14:03:54

标签: java swing jtree tablecellrenderer cellrenderer

简单地说:为什么下面的小例子在树形控件的第三个项目上显示浅灰色背景?

代码创建一个JTree,用三个字符串填充它(直接传入构造函数)并覆盖getCellRenderer()方法以返回自定义MyTreeCellRenderer类的实例,该类具有硬编码检查以设置背景第2行上任何单元格的颜色为浅灰色。但是在运行时,所有单元格都具有常规(白色)背景颜色。

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();
            }
        });
    }

}

1 个答案:

答案 0 :(得分:2)

DefaultTreeCellRendererJLabel的子类,必须为opaque才能显示颜色。

image

JComponent c = (JComponent) super.getTreeCellRendererComponent(tree,
    value,isSelected, expanded, leaf, row, hasFocus);
c.setOpaque(true);