2

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

代码创建一个 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();
            }
        });
    }

}
4

1 回答 1

2

DefaultTreeCellRenderer, 的子类JLabel, 必须不透明才能显示颜色。

图片

JComponent c = (JComponent) super.getTreeCellRendererComponent(tree,
    value,isSelected, expanded, leaf, row, hasFocus);
c.setOpaque(true);
于 2013-05-04T02:32:05.717 回答