2011-11-18 7 views

답변

0

MouseListener의 방법 (mouseReleased 등)에서 현재 위치가 포함 된 MouseEvent 개체를 받아야합니다. 이러한 값을 사용하지 않으려면 Component#getLocation 메서드를 사용해보십시오. 그렇지 않으면 Component#getLocationOnScreen하지만 절대 위치를 반환하므로 상대 값을 계산해야합니다.

+0

x = 0 및 y = 0을 반환합니다. 디버깅하는 동안 나는 개인 필드 desiredLocation 만 필요한 값을 저장하는 것으로 나타났습니다. 그러나 나는 그것에 접근하는 방법을 아직 모른다. – StKiller

+0

@Andrei 어떻게 표시합니까? 올바른 위치에 메뉴를 표시하는 코드가 있어야합니다. 맞습니까? – javanna

+0

오른쪽 클릭을 처리하고이 팝업 메뉴를 표시하는 JPanel이 있습니다. – StKiller

0

이 솔루션이 있지만, 보안 관리자가있는 경우는 (액세스 할 수 있도록 필드를 강제로) 실패 할 수 있기 때문에이 권장되지 않습니다 :

빨리 더 나은 도움말을
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; 
    } 
} 
관련 문제