我有一个窗口内嵌一个画布。窗口是全屏的,但画布不是。我需要获取画布内的鼠标位置,而不是窗口内的鼠标位置。该怎么做?
我需要每秒几次获取鼠标位置,即使鼠标没有移动,因此使用MouseMoved监听器不够好。
有没有办法在不调用任何mouselistener的情况下获取画布中的鼠标位置?
存储鼠标位置。如果它没有移动,则位置相同。然后使用鼠标移动的动作监听器来更新您存储的鼠标位置状态随着其改变。
Get the JFrame's components :
Component[] components = yourJFrame.getComponents();
Get your canvas(note : if you added something before adding the canvas,it wont be component 0. Example in Pseudocode add : button1, add:button2, add:canvas
- canvas=components[2]):
Component canvas = components[0];
Get the mouse's position :
int mouse_x=MouseInfo.getPointerInfo().getLocation().x-canvas.getLocationOnScreen().x;
int mouse_y=MouseInfo.getPointerInfo().getLocation().y-canvas.getLocationOnScreen().y;
完全没有必要使用监听器。 如果您对此有任何疑问,请随意评论。
getComponents()[0]
,而是可以直接检索this.canvas
的值。此外,如果窗口移动,这种方法是不起作用的。 - TheKodeToad