双击JTree节点并获取其名称 [英] Double-click a JTree node and get its name

查看:350
本文介绍了双击JTree节点并获取其名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何双击JTree节点并获取其名称?

How do I double-click a JTree node and get its name?

如果我调用 evt.getSource(),似乎返回的对象是JTree。我无法将其强制转换为DefaultMutableTreeNode。

If I call evt.getSource() it seems that the object returned is a JTree. I can't cast it to a DefaultMutableTreeNode.

推荐答案

来自 Java Docs


如果您有兴趣检测双击事件或
a用户点击某个节点,无论是否选中它,
我们建议您执行以下操作:

If you are interested in detecting either double-click events or when a user clicks on a node, regardless of whether or not it was selected, we recommend you do the following:



final JTree tree = ...;

MouseListener ml = new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        int selRow = tree.getRowForLocation(e.getX(), e.getY());
        TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
        if(selRow != -1) {
            if(e.getClickCount() == 1) {
                mySingleClick(selRow, selPath);
            }
            else if(e.getClickCount() == 2) {
                myDoubleClick(selRow, selPath);
            }
        }
    }
};
tree.addMouseListener(ml);

要从 TreePath 获取节点在你的情况下,可以使用 TreePath#getLastPathComponent

To get the nodes from the TreePath you can walk the path or simply, in your case, use TreePath#getLastPathComponent.

返回对象,因此您需要自己回送到所需的节点类型。

This returns an Object, so you will need to cast back to the required node type yourself.

这篇关于双击JTree节点并获取其名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆