2011-11-18 31 views

回答

0

在您的MouseListener的方法(mouseReleased等)中,您應該會收到一個包含當前位置的MouseEvent對象。如果你不想使用這些值,你可以嘗試使用Component#getLocation方法,否則Component#getLocationOnScreen但它返回絕對位置,那麼你需要計算相對值。

+0

它返回x = 0和y = 0。在調試期間,我注意到只有私人字段desiredLocation存儲所需的值。但我還不知道如何訪問它。 – StKiller

+0

@Andrei你怎麼看它顯示?你應該有一些代碼在正確的位置顯示菜單,對嗎? – javanna

+0

有一個JPanel,它處理右鍵單擊並顯示這個彈出式菜單。 – StKiller

0

有一個解決方案,但不建議,因爲如果有SecurityManager它可能會失敗(強制場可訪問):

public static Container getTopParent(@Nonnull Component c) { 
    Container lastNotNull = (Container) c; 
    Container p = c.getParent(); 
    if (p != null) 
     lastNotNull = p; 
    while(p != null) { 
     lastNotNull = p; 
     p = p.getParent(); 
    } 
    return lastNotNull; 
} 

public static int getClickedXThatInvokedPopup(@Nonnull ActionEvent ev) { 
    try { 
     JPopupMenu topParent = (JPopupMenu) getTopParent((Component) ev.getSource()); 
     java.lang.reflect.Field fieldX = topParent.getClass().getDeclaredField("desiredLocationX"); 
     fieldX.setAccessible(true); 
     int x = (Integer) fieldX.get(topParent); 
     Point p = new Point(x, 0); 
     SwingUtilities.convertPointFromScreen(p, topParent.getInvoker()); 
     return p.x; 
    } catch(NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) { 
     System.err.println("Cannot get clicked point: " + ex); 
     return -1; 
    } 
}