java.awt.event.MouseMotionListener只会为您提供有关鼠标在应用程序窗口内移动的信息。对于在该窗口外发生的事件,没有办法解决
MouseInfo.getPointerInfo。但是,您可以编写一个(可能是单例的)类,该类定期轮询指针信息并允许
MouseMotionListeners添加:
import java.awt.Component;import java.awt.MouseInfo;import java.awt.Point;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseMotionListener;import java.util.HashSet;import java.util.Set;import javax.swing.Jframe;import javax.swing.SwingUtilities;import javax.swing.Timer;public class MouseObserver { private static final int DELAY = 10; private Component component; private Timer timer; private Set<MouseMotionListener> mouseMotionListeners; protected MouseObserver(Component component) { if (component == null) { throw new IllegalArgumentException("Null component not allowed."); } this.component = component; timer = new Timer(DELAY, new ActionListener() { private Point lastPoint = MouseInfo.getPointerInfo().getLocation(); public synchronized void actionPerformed(ActionEvent e) { Point point = MouseInfo.getPointerInfo().getLocation(); if (!point.equals(lastPoint)) { fireMouseMotionEvent(point); } lastPoint = point; } }); mouseMotionListeners = new HashSet<MouseMotionListener>(); } public Component getComponent() { return component; } public void start() { timer.start(); } public void stop() { timer.stop(); } public void addMouseMotionListener(MouseMotionListener listener) { synchronized (mouseMotionListeners) { mouseMotionListeners.add(listener); } } public void removeMouseMotionListener(MouseMotionListener listener) { synchronized (mouseMotionListeners) { mouseMotionListeners.remove(listener); } } protected void fireMouseMotionEvent(Point point) { synchronized (mouseMotionListeners) { for (final MouseMotionListener listener : mouseMotionListeners) { final MouseEvent event = new MouseEvent(component, MouseEvent.MOUSE_MOVED, System.currentTimeMillis(), 0, point.x, point.y, 0, false); SwingUtilities.invokeLater(new Runnable() { public void run() { listener.mouseMoved(event); } }); } } } public static void main(String[] args) { Jframe main = new Jframe("dummy..."); main.setSize(100,100); main.setVisible(true); MouseObserver mo = new MouseObserver(main); mo.addMouseMotionListener(new MouseMotionListener() { public void mouseMoved(MouseEvent e) { System.out.println("mouse moved: " + e.getPoint()); } public void mouseDragged(MouseEvent e) { System.out.println("mouse dragged: " + e.getPoint()); } }); mo.start(); }}
请注意,尽管与标准的MouseMotionListener有一些明显的不同:
- 您只会收到
mouseMoved
事件,不会收到mouseDragged
事件。这是因为无法在主窗口之外接收有关单击的信息。 - 由于类似的原因,
modifiers
每个的MouseEvent
始终为0。 - 这同样适用于价值观
clickCount
,popupTrigger
,button
- 您将需要提供一个
java.awt.Component
将用作MouseEvent
s (伪)源的虚拟对象-null
此处不允许使用值。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)