【问题标题】:Scrolling a tree node to top of a scroll pane将树节点滚动到滚动窗格的顶部
【发布时间】:2011-07-12 13:47:28
【问题描述】:

我有一个 JTree 大约有 8 个以上的树节点(叶子)。要求是如果用户单击树节点,则选定的树节点将自动从任何位置滚动到滚动窗格的顶部。请帮忙!

【问题讨论】:

  • 您想更改您的 JTree 顺序吗?还是只是强制您的 JTree 节点位于包含 JScrollPane 之上?
  • scrollPathToVisiblescrollRootToVisible,但它们不一定会滚动到滚动窗格的顶部。
  • 不应更改树节点的顺序。假设底部的树节点是第 3 个树节点,当我单击打开它时,前 2 个树节点向上移动,单击的那个应该在滚动窗格的顶部。我尝试了所有其他方法,例如 scrollRectToVisible(rectBounds)、setRootVisible(boolean) 和 scrollPathToVisible(e.getPath()) 之类的方法。根据 Paulo 的说法,这些仅有助于滚动树节点的大小,而不是滚动到顶部。非常感谢这方面的任何帮助。

标签: java swing jscrollpane jtree


【解决方案1】:

在实际的JTree 上使用 scrollRectToVisible 方法。

例子:

tree.scrollRectToVisible(new Rectangle(0,0));

【讨论】:

  • 我用新的 Rectangle(0,0) 进行了测试。完整的面板在树节点下可见,但节点尚未移动到滚动面板的顶部。
  • @Mani,SSCCE 会很有帮助。
  • 您能解释一下这个SSCCE吗?这在这方面有什么帮助?
  • sscce.org(该网站很好地解释了它的帮助)
【解决方案2】:

这个问题很久以前就问过了,不知道你还需要这个吗……

我了解您遇到的问题,问题是:树选择侦听器无法按您预期的那样工作。您必须通过注册鼠标侦听器来检测单击事件。像这样的:

tree = new JTree();
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    MouseListener ml = new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            int selRow = tree.getRowForLocation(e.getX(), e.getY());
            currentRow = selRow;
            TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
            if (selRow != -1) {
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(selPath.getLastPathComponent());
                if (node != null && node.isLeaf()) {
                    String stringId = '<sting-id-of-node-you-wish-to-scroll-to>';
                    TreePath tp = tree.getNextMatch(stringId, currentRow, Position.Bias.Forward);
                    if (tp == null) {
                        tp = tree.getNextMatch(stringId, currentRow, Position.Bias.Backward);
                    }
                    tree.setSelectionPath(tp);
                    tree.scrollPathToVisible(tp);
                }
            }
        }
    };
    tree.addMouseListener(ml);

干杯!

【讨论】:

    【解决方案3】:

    如前所述:所有 scrollXXToVisible 方法都会滚动以使给定的 XX 在某处可见,它们不支持更精细的控制,如 f.i。 “应该是可见区域中的第一个节点”。

    您必须自己实现该功能,例如

    TreePath path = tree.getSelectionPath();
    if (path == null) return;
    Rectangle bounds = tree.getPathBounds(path);
    // set the height to the visible height to force the node to top 
    bounds.height = tree.getVisibleRect().height;
    tree.scrollRectToVisible(bounds);
    

    注意:当节点上的鼠标事件从其脚下移动时,这样做可能会让用户感到厌烦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-06
      • 1970-01-01
      相关资源
      最近更新 更多