在Swing程序中通常通过鼠标事件的MouseEvent对象,来获取鼠标的坐标,这种情况只能在窗体事件中获取。如果要在窗体最小化或窗体失去焦点后仍要获取鼠标位置的话,就要使用MouseInfo这个对象了。
MouseInfo 提供获取有关鼠标信息的方法,如鼠标指针位置和鼠标按钮数。
- getPointerInfo() :返回表示鼠标指针当前位置的
PointerInfo
实例 - getNumberOfButtons() :返回鼠标上的按钮数。在没有鼠标的系统上,返回
-1
。
示例代码:
while(true){
Point point = MouseInfo.getPointerInfo().getLocation();
System.out.println(point);
try { Thread.sleep(100); } catch (InterruptedException e) { }
}