获取面板的坐标

Getting the coordinates of the panel

使用mouseevents,我能够得到框架的x和y坐标,但我无法得到面板的x和y坐标。下面的代码是我获取框架的 x 和 y 坐标。

public void mouseMoved(MouseEvent e) {
    x = e.getX();
    y = e.getY();
    text = Integer.toString(x) +","+Integer.toString(y);

    Frame.frame.repaint();

}

下面的代码是我试图获取面板的 x 和 y 坐标,但它绘制的是 0。 Paint.paint 是我的 jpanel 的名称。我不知道我做错了什么。如果可以请帮忙。

public void mouseMoved(MouseEvent e) {
    x = Paint.paint.getX();
    y = Paint.paint.getY();
    text = Integer.toString(x) +","+Integer.toString(y);

    Frame.frame.repaint();

}

如果我理解正确,您的 MouseListener 已在 JFrame 中注册,并且您希望获得相对于 JFrame 中包含的 JPanel 的 x/y。 MouseEvent 中的 x 和 y 指的是注册了 MouseListener 的组件。如果你在Parent容器上注册了一个MouseListener,用来获取MouseEvent相对于子Component的坐标,你可以使用SwingUtilities来转换坐标

public void mousePressed(MouseEvent e){
    Point childCoordinate = SwingUtilities.convertPoint(parent, e.getPoint(), child);
}