2011-03-10 42 views
3

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

+0

你想改变你的JTree命令吗?或者仅仅是强制你的JTree节点位于包含JScrollPane的顶部? – Riduidel 2011-03-10 09:31:20

+0

有'scrollPathToVisible'和'scrollRootToVisible',但它们不会一定滚动到Scrollpane的顶部。 – 2011-03-10 10:46:03

+0

不应更改树节点的顺序。假设树节点在底部,它是一些第三个树节点,当我点击打开它时,前面的2个树节点向上移动,点击的节点应该在滚动窗格的顶部。我尝试了所有其他类似scrollRectToVisible(rectBounds),setRootVisible(boolean)和scrollPathToVisible(e.getPath())的方法。根据Paulo的说法,只有这些帮助才能滚动树节点的大小,而不是滚动到顶部。在这方面的任何帮助真的很感激。 – 2011-03-11 05:05:11

回答

2

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

例子:

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

试过这个不行...... – 2011-03-15 05:15:26

+0

@Mani,“不工作”不是很具体。 – jzd 2011-03-15 11:04:00

+0

我测试了新的矩形(0,0)。完整面板在树节点下可见,但该节点尚未移动到滚动窗格的顶部。 – 2011-03-21 12:48:12

1

这个问题被问得很久以前,我不知道你是否还需要这个......

我知道你有问题,这个问题是这:树选择监听器不能像你所期望的那样工作。您必须通过注册鼠标侦听器来检测单击事件。类似这样的:

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); 

请注意:因为它从它的脚下移动目标反应到节点上的鼠标事件这样做可能是恼人的用户。