像Android可扩展列表视图一样更改Tree的叶子的背景颜色

时间:2019-07-31 00:45:47

标签: jtree

在JTree中选择叶子节点时,我编写了以下代码来填充背景色。 但是,只有当我单击下面红色区域中的叶子图标和叶子节点时,背景颜色才会更改。 发生这种情况似乎是因为在红色区域之外单击TreePath时,它返回null。当我在叶子节点所在的行上的任意位置单击时,我想填充背景色。

JTree menuTree = new JTree(root) {
    private Color SELECTED_COLOR = Color.DARK_GRAY;

    @Override
    public void paintComponent(Graphics g) {
        g.setColor(getBackground());
        g.fillRect(0, 0, getWidth(), getHeight());

        if (getSelectionCount() > 0) {
            g.setColor(SELECTED_COLOR);
            // @see http://ateraimemo.com/Swing/TreeRowSelection.html

            for (int i : getSelectionRows()) {
                Rectangle r = getRowBounds(i);
                g.fillRect(0, r.y, getWidth(), r.height);
            }
        }

        super.paintComponent(g);

        if (getLeadSelectionPath() != null) {
            Rectangle r = getRowBounds(getRowForPath(getLeadSelectionPath()));
            g.setColor(hasFocus() ? SELECTED_COLOR.darker() : SELECTED_COLOR);
            g.drawRect(0, r.y, getWidth() - 1, r.height - 1);
        }
    }
};

图片在链接下方。

JTree Background Color

0 个答案:

没有答案
相关问题