JTree右键的一些用法

先建一个菜单对象,处理JTree控件鼠标事件,然后将菜单显示出来
JPopupMenu popup = new JPopupMenu();
JMenuItem modify = new JMenuItem("modify");
modify.setActionCommand("modify");
modify.addActionListener(this);
popup.add(modify);

1: 左键选中然后再右键去操作
tree.addMouseListener(new MouseAdapter() {
   public void mousePressed(MouseEvent e) {
    if (e.getButton() == e.BUTTON3) {  //BUTTON3是鼠标右键
      DefaultMutableTreeNode node =  (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
      pmn.show(e.getComponent(),e.getX(),e.getY());
    }
   }
  });

2: 直接右击
public void jTree1_mousePressed(MouseEvent e) {
    TreePath tp=tree.getPathForLocation(e.getX(),e.getY());
   if (tp != null) {
          tree.setSelectionPath(tp);
          DefaultMutableTreeNode node =  (DefaultMutableTreeNode)tp.getLastPathComponent()
   } 
   pmn.show(e.getComponent(),e.getX(),e.getY());
    }
   }
  });

你可能感兴趣的:(JTree)