java 找到鼠标xy坐标的简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10457817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easy way to find x y coordinates of mouse?
提问by Ryley Matos
So basically I'm making a game which main class has a loop that runs 60 times per second
所以基本上我正在制作一个游戏,其中主类有一个每秒运行 60 次的循环
I need an easy way to find the x y coordinates of the mouse so i can draw something over that particular coordinates.
我需要一种简单的方法来找到鼠标的 xy 坐标,以便我可以在该特定坐标上绘制一些东西。
Is there any good way to do this?
有什么好的方法可以做到这一点吗?
回答by matthewtory
This code wont actually work if you try and run it, but it shows you how to get the position of the mouse X and Y, as integers
如果您尝试运行该代码,该代码实际上将不起作用,但它向您展示了如何以整数形式获取鼠标 X 和 Y 的位置
import java.awt.MouseInfo;
public class testmouse {
public static void main(String[] args){
int mouseY = MouseInfo.getPointerInfo().getLocation().y;
int mouseX = MouseInfo.getPointerInfo().getLocation().x;
}
}
回答by Andrew Thompson
Add a MouseMotionListener
to the game area and watch for mouseMoved(MouseEvent)
.
MouseMotionListener
向游戏区域添加并注意mouseMoved(MouseEvent)
。