先建一個菜單對象,處理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());
}
}
});