JTree DefaultTreeCellRenderer颜色基于级别

时间:2015-07-16 12:26:37

标签: java swing jtree

我正在扩展DefaultTreeCellRenderer以根据级别绘制节点背景,但是我目前只能获取当前行而不是当前级别。

如何在getTreeCellRendererComponent(JTree aTree,Object aValue,boolean aSelected,boolean aExpanded,boolean aLeaf,int aRow,boolean aHasFocus)函数中获取当前级别?

在下面的实例中,我只能基于行替换节点的背景,如何在树上获得级别,如果级别== 1将背景设置为黄色?

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;

public class Testing
{
    public void buildGUI()
    {
        final MyJTree tree = new MyJTree();
        JFrame f = new JFrame();
        f.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
        f.setSize(200, 200);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

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

class MyJTree extends JTree
{
    public MyJTree()
    {
        super();
        setCellRenderer(new NiceTreeCellRenderer());
    }
}

class NiceTreeCellRenderer extends DefaultTreeCellRenderer
{

    DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();

    @Override
    public Component getTreeCellRendererComponent(JTree aTree, Object aValue, boolean aSelected,
            boolean aExpanded, boolean aLeaf, int aRow, boolean aHasFocus)
    {
        JPanel panel = new JPanel(); // Create a new panel where we will show the data.
        String text = (String) ((DefaultMutableTreeNode) aValue).getUserObject();
        panel.add(new JLabel(text)); // Actually show the data.

        // If the value is not null and is a tree node and a leaf then paint it.
        if ((aValue != null) && (aValue instanceof DefaultMutableTreeNode) && aLeaf)
        {
                if (aRow % 2 == 0)
                {
                    panel.setBackground(Color.WHITE);
                }
                else
                {
                    panel.setBackground(new Color(230, 230, 230));
                }
            panel.setEnabled(aTree.isEnabled());
            return panel;
        }
        // For everything else use default renderer.
        return defaultRenderer.getTreeCellRendererComponent(aTree, aValue, aSelected, aExpanded, aLeaf,
                aRow, aHasFocus);
    }
}

1 个答案:

答案 0 :(得分:1)