2012-04-11 76 views
3

我想显示弹出框在右键单击JTree节点只,而不是整个JTree组件。 当用户右键单击JTree节点时弹出框出现。如果他右击JTree中的空白区域,则不应该出现。那么为什么我只能检测到JTree节点的鼠标事件。我在网上搜索过很多次,但找不到解决方案,请帮助我。显示弹出框右键单击JTree节点摆动

感谢。

回答

13

这里有一个简单的方法:

public static void main (String[] args) 
{ 
    JFrame frame = new JFrame(); 

    final JTree tree = new JTree(); 
    tree.addMouseListener (new MouseAdapter() 
    { 
     public void mousePressed (MouseEvent e) 
     { 
      if (SwingUtilities.isRightMouseButton (e)) 
      { 
       TreePath path = tree.getPathForLocation (e.getX(), e.getY()); 
       Rectangle pathBounds = tree.getUI().getPathBounds (tree, path); 
       if (pathBounds != null && pathBounds.contains (e.getX(), e.getY())) 
       { 
        JPopupMenu menu = new JPopupMenu(); 
        menu.add (new JMenuItem ("Test")); 
        menu.show (tree, pathBounds.x, pathBounds.y + pathBounds.height); 
       } 
      } 
     } 
    }); 
    frame.add (tree); 


    frame.pack(); 
    frame.setLocationRelativeTo (null); 
    frame.setVisible (true); 
} 
+0

这是更好地使用' MouseEvent#isPopupTrigger',然后是'isRightMouseButton'方法。 – Robin 2012-04-11 08:15:46

+0

这实际上取决于情况。但是对于默认的弹出菜单是的,它更好。 – 2012-04-11 08:20:25

+0

+1,希望我对'JTree' :-)有很多了解。对我来说这是一个很好的答案:-) – 2012-04-11 13:36:14

2

只是因为我最近偶然发现了这一点,我认为这是比现有的答案更容易一点点:

public static void main(String[] args) { 
    JFrame frame = new JFrame(); 
    final JTree tree = new JTree(); 

    JPopupMenu menu = new JPopupMenu(); 
    menu.add(new JMenuItem("Test")); 
    tree.setComponentPopupMenu(menu); 
    frame.add(tree); 

    frame.pack(); 
    frame.setLocationRelativeTo(null); 
    frame.setVisible(true); 
} 
+1

它肯定比较容易,但我记得在某些特定的Swing组件上遇到了一些问题。另外,您无法控制此菜单的显示方式,位置和时间 - 您只能修改菜单的内容。在你的例子中显示菜单的代码隐藏在L&F实现中(甚至不是组件本身或它的UI),它会默认检查'event.isPopupTrigger()',除了其他可能的问题,在某些系统上不起作用。 – 2015-10-07 10:37:31

+0

我不是一个Swing-pro,我只是认为简单的解决方案不应该保密,如果它在大多数情况下工作...感谢指出问题 – 2015-10-07 15:37:50