4

我正在尝试获取组件相对于其父级的坐标。例如,当我有一个大小为500x500的JFrame时,它​​有一个孩子 - JPanel - 在[50, 10]我应该得到[50, 10]作为结果。不管看起来多么容易,我总是得到错误的坐标([0, 0][3, 24])。

这是我的 JPanel 的代码:

class MyPanel extends JPanel implements MouseListener { 
    private Component parent;   
    private String strName;

    public MyPanel(Component pr, String name, int w, int h) {
        super();

        parent = pr;
        strName = new String(name);

        this.setLayout(null);
        this.setSize(w, h);
        this.setBackground(Color.WHITE);
        this.addMouseListener(this);

        this.setVisible(true);
    }

    /* MouseListener implementation */
    public void mouseClicked(MouseEvent event) {
            int x = event.getX(); int y = event.getY();
            Point pnt = new Point(SwingUtilities.convertPoint(this, new Point(0, 0), parent));
            System.out.println(strName + ":" + pnt);    
    }

    public void mouseEntered(MouseEvent event) { }

    public void mouseExited(MouseEvent event) { }

    public void mousePressed(MouseEvent event) { }

    public void mouseReleased(MouseEvent event) { }
}

有任何想法吗?

Java 二进制和源代码 (*.tar.xz)

4

1 回答 1

5

尝试这个:

Point pnt = new Point(SwingUtilities.convertPoint(this, event.getPoint(), parent));

isnatead 使用(至少在提供的代码段中从未使用过 BTW):

    int x = event.getX();
    int y = event.getY();

你不应该这样做:

Point pnt = new Point(SwingUtilities.convertPoint(this, new Point(0,0), parent));

否则返回的坐标将始终与 (0,0) 有关。

您也可以这样做(我认为您会这样做,但忘记了 x 和 y :P):

    int x = event.getX();
    int y = event.getY();
    Point pnt = new Point(SwingUtilities.convertPoint(this,
                                               new Point(x,y), parent));

编辑:

如果我明白你想要什么,那么为什么要打扰所有这些代码呢?在每个JPanelsMouseListenermouseClicked()这样做:

public void mouseClicked(MouseEvent event) {
    System.out.println(this.getX()+" "+this.getY());//print x and why co-ords for MyJpanel
}
于 2012-08-21T19:58:16.617 回答