我正在尝试获取组件相对于其父级的坐标。例如,当我有一个大小为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) { }
}
有任何想法吗?