【问题标题】:How to add gaps to a JTree如何向 JTree 添加间隙
【发布时间】:2011-03-04 00:59:12
【问题描述】:

我的问题是这样的

我正在尝试创建一个并排显示两棵树的组件。这两棵树通常非常相似,但可能会有一两个不同之处。在有区别的地方,即一个分支但另一个没有,我希望没有分支的树为它显示一个空白空间,也为它的每个丢失的孩子显示一个空白空间。

所以它可能看起来像

左树右树 ------------ ------------- + 根 + 根 | | --孩子A --孩子A | | --孩子B | | | --孩子 C --孩子 C

使用自定义渲染器删除那些应该是空白的行的文本和图标相对简单。但是,这仍然留下将孩子连接到父母垂直线的水平线。这是我的问题。

左树右树 ------------ ------------- + 根 + 根 | | --孩子A --孩子A | | --孩子 B --

在这个简单的例子中它可能是裸露的,但是当丢失的分支也有孩子时,我最终会得到很多连接间隙的小线。

我认为一个潜在的替代方法是为每棵树创建一列 JTreeTable,并为缺失的分支清空单元格。虽然这意味着垂直线的一部分也会丢失。

我们将非常感谢任何帮助、想法或 cmets。谢谢。

【问题讨论】:

    标签: java user-interface swing jtree


    【解决方案1】:

    考虑以下几点:

    class ReticentTreeUI extends BasicTreeUI {
    
        private Set<Integer> hiddenRows = new HashSet<Integer>();
    
        public void hideRow(int row) {
            hiddenRows.add(row);
        }
    
        @Override
        protected void paintHorizontalPartOfLeg(Graphics g,
            Rectangle clipBounds, Insets insets, Rectangle bounds,
            TreePath path, int row, boolean isExpanded,
            boolean hasBeenExpanded, boolean isLeaf) {
            if (!hiddenRows.contains(row)) {
                super.paintHorizontalPartOfLeg(g, clipBounds, insets, bounds,
                    path, row, isExpanded, hasBeenExpanded, isLeaf);
            }
        }
    
        @Override
        protected void paintRow(Graphics g, Rectangle clipBounds,
            Insets insets, Rectangle bounds, TreePath path, int row,
            boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) {
            if (!hiddenRows.contains(row)) {
                super.paintRow(g, clipBounds, insets, bounds, path, row,
                    isExpanded, hasBeenExpanded, isLeaf);
            }
        }
    
        @Override
        protected void paintExpandControl(Graphics g, Rectangle clipBounds,
            Insets insets, Rectangle bounds, TreePath path, int row,
            boolean isExpanded, boolean hasBeenExpanded, boolean isLeaf) {
            if (!hiddenRows.contains(row)) {
                super.paintExpandControl(g, clipBounds, insets, bounds,
                    path, row, isExpanded, hasBeenExpanded, isLeaf);
            }
        }
    }
    

    使用示例:

        JTree tree = new JTree();
        ReticentTreeUI ui = new ReticentTreeUI();
        tree.setUI(ui);
        ui.hideRow(2);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 2014-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多