我有一个JTree
,其中包含超过8个树节点(叶子)。要求是,如果用户单击树节点,则所选树节点将自动从任何位置滚动到滚动窗格的顶部。请帮忙!
答案 0 :(得分: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);
注意:响应节点上的鼠标事件,这样做可能会让用户感到烦恼,因为它会从目标脚下移动目标。
答案 1 :(得分:2)
在实际JTree
上使用scrollRectToVisible方法。
示例:
tree.scrollRectToVisible(new Rectangle(0,0));
答案 2 :(得分:1)
很久以前就问过这个问题了,我不知道你是否仍然需要这个......
我理解你遇到的问题,问题是:树选择听众不会像你期望的那样工作。您必须通过注册鼠标侦听器来检测click事件。像这样:
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);
干杯!