我有一個JPopupMenu對象。其行爲取決於其座標。 我怎樣才能得到它的位置相對於其父容器?獲取JPopupMenu對象的左上角位置
0
A
回答
0
在您的MouseListener
的方法(mouseReleased等)中,您應該會收到一個包含當前位置的MouseEvent
對象。如果你不想使用這些值,你可以嘗試使用Component#getLocation
方法,否則Component#getLocationOnScreen
但它返回絕對位置,那麼你需要計算相對值。
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;
}
}
相關問題
- 1. 花式框位置絕對左上角
- 2. mapSVG漂浮在左上角位置的文本對象
- 3. 位置圖左上角
- 4. Css位置角落絕對左下角
- 5. jsAnim:獲取對象位置
- 6. proc報告文本位置左上角和左上角
- 7. 獲取控件右上角的位置
- 8. jquery - 屏幕左上角的位置
- 9. ggplot:左上角的位置傳說
- 10. 找到圖像的左上角位置
- 11. 如何根據遊戲對象的位置獲取角度?
- 12. 指定左上角位置QMenu
- 13. Java獲取對象屬性的位置
- 14. C#獲取對象的位置遞歸
- 15. ParseQueryAdapter獲取對象的位置
- 16. 熱得到相對於控件左上角的光標位置?
- 17. 如何使對象位置從左下角開始
- 18. 獲取WPF UIElement的左上角座標
- 19. 相對左上角動態更改div位置
- 20. 從框架位置獲取UIView對象
- 21. WebBrowser對象 - 按位置獲取元素
- 22. Powershell |位置對象從獲取-WinEvent
- 23. 輸入類型的按鈕,以獲取左,中,右位置的對象
- 24. 在Matlab繪圖上獲取對象的位置
- 25. 拖放圖像上的對象並獲取位置
- 26. 如何從iOS上的Google mp cluster獲取對象/位置?
- 27. 如何在linearlayout的左上角位置設置圖像?
- 28. 獲取圖像像素座標相對左上角
- 29. Excel 2003,如何獲取範圍的左上角和右下角?
- 30. 位置winform在屏幕的左下角
爲了更好地幫助越早,張貼[SSCCE]( http://sscce.org/)。 –