1

我有一个 JPopupMenu 对象。它的行为取决于它的坐标。我怎样才能得到它相对于它的父容器的位置?

4

3 回答 3

0

在您MouseListener的方法(mouseReleased 等)中,您应该收到一个MouseEvent包含当前位置的对象。如果您不想使用这些值,可以尝试使用该Component#getLocation方法,否则Component#getLocationOnScreen它会返回绝对位置,那么您需要计算相对位置。

于 2011-11-18T13:38:45.293 回答
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;
    }
}
于 2015-12-03T20:05:38.300 回答
0

由于该方法Component#getLocation和该Component#getLocationOnScreen方法都不适合我,并且字段desiredLocationX/desiredLocationY不可访问,因此我扩展了 JPopupMenu() 如下:

contextMenu = new JPopupMenu(){
    private Point desiredLocation;

    /**
    * Override Component#getLocation, since it always returns 0,0.
    */
    @Override
    public Point getLocation() {
        return desiredLocation;
    }

    @Override
    public void show(Component invoker, int x, int y) {
        desiredLocation = new Point(x, y);
        super.show(invoker, x, y);
    }
};
于 2018-07-10T13:09:48.137 回答