使用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();
}
答案 0 :(得分:2)
如果我理解正确,您的MouseListener是在JFrame中注册的,并且您希望获得相对于JFrame中包含的JPanel的x / y。 MouseEvent中的x和y指的是注册了MouseListener的Component。如果您在Parent容器上注册了MouseListener,并且要获取MouseEvent相对于子Component的坐标,则可以使用SwingUtilities转换坐标
public void mousePressed(MouseEvent e){
Point childCoordinate = SwingUtilities.convertPoint(parent, e.getPoint(), child);
}