JTree与mousemotionlistener

时间:2012-10-22 09:11:43

标签: java swing tooltip jtree mouse-listeners

我有一个JTree,我希望在用户将鼠标悬停在树节点上时向用户显示一些描述。

我从文档中读到,我们可以使用MouseMotionListener来实现此目的。但是,如何获取移动鼠标的节点的值?

任何指针都非常有用。

2 个答案:

答案 0 :(得分:2)

MouseEvent获取节点值的一种方法是获取鼠标x,y位置的TreePath并从此路径获取最后一个路径组件。

这看起来像这样:

import javax.swing.tree.TreePath;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JTree;
...

final JTree tree = new ...
tree.addMouseMotionListener(new MouseMotionListener() {

        @Override
        public void mouseMoved(MouseEvent e)
        {
            TreePath path = tree.getPathForLocation(e.getX(), e.getY());
            if(path == null || path.getLastPathComponent() == null)
            {
                return;
            }

            Object nodeHoveredOver = path.getLastPathComponent();
            System.out.println(path.getLastPathComponent());
        }

        @Override
        public void mouseDragged(MouseEvent e)
        {
            ...                
        }
});

但是,如果您想将描述显示为工具提示,那么此this solution可能会更适合您。

答案 1 :(得分:1)

查看JTree#getTooltipText实施:

public String getToolTipText(MouseEvent event) {
    String tip = null;

    if(event != null) {
        Point p = event.getPoint();
        int selRow = getRowForLocation(p.x, p.y);
        TreeCellRenderer       r = getCellRenderer();

        if(selRow != -1 && r != null) {
            TreePath     path = getPathForRow(selRow);
            Object       lastPath = path.getLastPathComponent();
            Component    rComponent = r.getTreeCellRendererComponent
                (this, lastPath, isRowSelected(selRow),
                 isExpanded(selRow), getModel().isLeaf(lastPath), selRow,
                 true);

            if(rComponent instanceof JComponent) {
                //...

                tip = ((JComponent)rComponent).getToolTipText(newEvent);
            }
        }
    }
    // No tip from the renderer get our own tip
    if (tip == null) {
        tip = getToolTipText();
}
    return tip;
}

因此,尊重渲染器指定的工具提示文本。