在canvas中获取鼠标位置(Java)

3

我有一个窗口内嵌一个画布。窗口是全屏的,但画布不是。我需要获取画布内的鼠标位置,而不是窗口内的鼠标位置。该怎么做?

我需要每秒几次获取鼠标位置,即使鼠标没有移动,因此使用MouseMoved监听器不够好。

有没有办法在不调用任何mouselistener的情况下获取画布中的鼠标位置?

2个回答

5

存储鼠标位置。如果它没有移动,则位置相同。然后使用鼠标移动的动作监听器来更新您存储的鼠标位置状态随着其改变。


2
这里有一个简单的例子,介绍我如何实现它。首先:
  • 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接