tags:

views:

491

answers:

3

My boilerplate listener:

class MyMouseMotionListener implements MouseMotionListener {
public void mouseDragged(MouseEvent e) {
 System.out.println("Dragged...");
}

public void mouseMoved(MouseEvent e) {
 System.out.println("Moved...");
}}

Simple enough, but what do I add it to in order to listen to system-wide events? I've been researching are things like the GraphicsDevice and AccessibleContext subclasses -- they don't offer the addition of MouseMotionListeners directly but I was hoping they might give me some idea as to how I could implement this.

Edit: This isn't at all event-based but I've found this:

MouseInfo.getPointerInfo().getLocation()

Does actually return the mouse position outside the context of my app, even when the app itself does not have focus. Is there any way to observe this and dispatch an event if its value has changed?

+1  A: 

UPDATE: You could poll MouseInfo for position but you'll never get button state. You will need to use native code to get button state.

I do not think there is any way without using native code to listen to the mouse cursor outside of the cotainer hierarchy of your application.

basszero
+1  A: 

Yes; use Toolkit.addAWTEventListener(new MyMouseMotionListener(), AWTEvent.MOUSE_MOTION_EVENT_MASK);

See http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#addAWTEventListener(java.awt.event.AWTEventListener, long) (I can't get the link to work, so you'll have to copy and paste it).

Note: as basszero said, this only works inside your container hierarchy.

Michael Myers
This only works WITHIN your AWT/Swing window. It is unclear if the OP wants system-wide or java-wide events.
basszero
Yes, you're right that that listening to all system events would be impossible without native code (and maybe even with it, but I don't know). This is the next best thing.
Michael Myers
When I implement AWTEventListener as my mouse movement listener and attach it using Toolkit, it seems to have the exact same effect. Using either method, I'm still stuck in the context of the app itself. Any other thoughts?
spligak
By design, Java can only do things which the host OS allow it to do. This sort of thing requires native code to bypass Java's restrictions (plus it has to be OS-specific code). I'm afraid there is no other way to do it.
Michael Myers
A: 

If you want to listen/capture all mouse events on the system (as in, not just your application window), you'll need a mouse hook.

cbrulak