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