【问题标题】:Java: JTree with plus/minus icons for expansion and collapse?Java:带有用于展开和折叠的加号/减号图标的 JTree?
【发布时间】:2011-09-29 05:56:04
【问题描述】:

如何使我的 Jtree 看起来像下面的东西,带有允许展开和折叠的加号和减号图标?

目前,默认的 JTree 只有在双击时才会展开和折叠。我想覆盖此双击以获得另一个功能,并让用户仅通过单击下面的减号和加号图标来展开/折叠树。

【问题讨论】:

    标签: java swing jtree


    【解决方案1】:

    您必须更改 L&F 的 Tree.collapsedIconTree.expandedIcon 属性并提供您自己的图标:

    UIManager.put("Tree.collapsedIcon", new IconUIResource(new NodeIcon('+')));
    UIManager.put("Tree.expandedIcon",  new IconUIResource(new NodeIcon('-')));
    

    这是我使用的图标,它是一个简单的正方形,里面有一个 +/-:

    public class NodeIcon implements Icon {
    
        private static final int SIZE = 9;
    
        private char type;
    
        public NodeIcon(char type) {
            this.type = type;
        }
    
        public void paintIcon(Component c, Graphics g, int x, int y) {
            g.setColor(UIManager.getColor("Tree.background"));
            g.fillRect(x, y, SIZE - 1, SIZE - 1);
    
            g.setColor(UIManager.getColor("Tree.hash").darker());
            g.drawRect(x, y, SIZE - 1, SIZE - 1);
    
            g.setColor(UIManager.getColor("Tree.foreground"));
            g.drawLine(x + 2, y + SIZE / 2, x + SIZE - 3, y + SIZE / 2);
            if (type == '+') {
                g.drawLine(x + SIZE / 2, y + 2, x + SIZE / 2, y + SIZE - 3);
            }
        }
    
        public int getIconWidth() {
            return SIZE;
        }
    
        public int getIconHeight() {
            return SIZE;
        }
    }
    

    【讨论】:

    • 哇!你让它变得超级简单
    • 性感!正是人们所需要的。
    【解决方案2】:

    带有允许展开和折叠的加号和减号图标?

    这些是 Windows LAF 的默认图标。其他 LAF 有不同的图标。

    您可以使用 UIManager 设置自己的图标。见UIManager Defaults

    或者您可以只为单个 JTree 使用自定义图标。见Customizing a Tree's Display

    让用户只需点击下面的减号和加号图标即可展开/折叠树。

    这是默认行为。

    【讨论】:

    • 但是如何覆盖双击行为而不是展开行呢?仅当您单击 +/- 箭头时才会发生扩展;双击该行的其他任何地方应该做一些不同的事情(例如在其他视图中打开选定的项目)。
    • 我不知道如何阻止双击折叠/展开,同时在单击 +/- 时允许折叠/展开。
    【解决方案3】:

    或者简单地认为:)

    class SourceListTreeUI extends BasicTreeUI
    {
    
        int offset = 10;
    
        protected int getRowX(int row, int depth)
        {
            return totalChildIndent * (depth + offset);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      • 2022-11-08
      相关资源
      最近更新 更多