2012-04-11 46 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

相關問題