import java.awt.BorderLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent;import javax.swing.*; import javax.swing.tree.TreePath;public class T { public static void main(String[] args) { final JPopupMenu popup = new JPopupMenu(); popup.add(new JMenuItem("MenuItem-1")); popup.add(new JMenuItem("MenuItem-2")); popup.add(new JMenuItem("MenuItem-3")); popup.add(new JMenuItem("MenuItem-4"));
final JTree tree = new JTree(); tree.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { TreePath treePath = tree.getPathForLocation(e.getX(), e.getY()); if (treePath != null) { tree.setSelectionPath(treePath); popup.show(tree, e.getX(), e.getY()); } } }); JScrollPane sp = new JScrollPane(tree);
JFrame f = new JFrame("TreePopupMenuTest"); f.getContentPane().add(sp, BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } }
public void subDeptList_mouseClicked(MouseEvent e) { // For this example event, we are checking for right-mouse click. if (e.getModifiers() == Event.META_MASK) { // JPopupMenu must be added to the component whose event is chosen. this.add(deptControlMenu); // Make the jPopupMenu visible relative to the current mouse position in the container. deptControlMenu.show(this, e.getX(), e.getY()); } } 帮助文档中的例子 Event.META_MASK就是右键
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;import javax.swing.*;
import javax.swing.tree.TreePath;public class T
{
public static void main(String[] args)
{
final JPopupMenu popup = new JPopupMenu();
popup.add(new JMenuItem("MenuItem-1"));
popup.add(new JMenuItem("MenuItem-2"));
popup.add(new JMenuItem("MenuItem-3"));
popup.add(new JMenuItem("MenuItem-4"));
final JTree tree = new JTree();
tree.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e)
{
TreePath treePath = tree.getPathForLocation(e.getX(), e.getY());
if (treePath != null) {
tree.setSelectionPath(treePath);
popup.show(tree, e.getX(), e.getY());
}
}
});
JScrollPane sp = new JScrollPane(tree);
JFrame f = new JFrame("TreePopupMenuTest");
f.getContentPane().add(sp, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
{
// For this example event, we are checking for right-mouse click.
if (e.getModifiers() == Event.META_MASK)
{
// JPopupMenu must be added to the component whose event is chosen.
this.add(deptControlMenu);
// Make the jPopupMenu visible relative to the current mouse position in the container.
deptControlMenu.show(this, e.getX(), e.getY());
}
}
帮助文档中的例子
Event.META_MASK就是右键