如何在DefaultMutableTreeNode上获得鼠标侦听器?

时间:2012-10-11 18:51:27

标签: java jtree mouselistener

我知道我可以将一个mouseListener添加到Jtree,但是我需要双击他的一个元素和doSomething();

2 个答案:

答案 0 :(得分:5)

来自documentation of JTree

  

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

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

答案 1 :(得分:1)

检查: -

  public class NetworkTree extends JPanel implements TreeSelectionListener {
  private JTree tree;
  private static int PANEL_WIDTH=250;
  private static int PANEL_HEIGHT=500;
private static String lineStyle = "Horizontal";

public NetworkTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode(new Site(
                1,1,"Network","",3));
getSubNodes(top,0);
tree = new JTree(top);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(this);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);

tree.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent me) {
    newNodeSelected();
  }
});
 }
.....
    public void newNodeSelected() {
   JOptionPane.showMessageDialog(null,"Hello");
}

.....     }