如何获取画布的准确位置(Java)
在我的代码中,我使用鼠标坐标与程序交互。从那里,必须在鼠标的位置绘制一些东西。但是,Canvas 的 getX()/getY() 方法返回保存 Canvas 的窗口的值,但是当我去绘制时,(0,0) 稍微位于右侧和下方(经过条形图)窗口左上角,导致偏离正确位置大约 30 像素。有没有办法调和差异,或者我应该简单地全屏窗口或使用其他方法来完全回避问题?
In my code, I use mouse coordinates to interact with the program. From there, something must be drawn at the mouse's location. However, the getX()/getY() methods for the Canvas return the values of the window holding the Canvas, but when I go to draw, (0,0) is located slightly to the right and below (past the bars) the top left of the window, resulting in being approximately 30 pixels off of the correct location. Is there a way to reconcile the differences, or should I simply fullscreen the window or use some other method to sidestep the problem altogether?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我猜您已将
MouseListener
和MouseMotionListener
注册到了窗口。将它们注册到Canvas
中,您将获得相对于该小部件的坐标。请参阅此示例代码。I guess you registered the
MouseListener
andMouseMotionListener
to the window. Register them for theCanvas
and you get coordinates relative to this widget. See this sample code.使用 getX()/getY() 方法,但在 mosueDragged/click 侦听器内,处理事件。
检查此示例(参数):
然后在鼠标按下事件上使用该方法:
Using the getX()/getY() methods but inside a mosueDragged/click listener, working with an event.
Check this example (the parameters):
Then the method is used, on a Mouse pressed event: