rockclimber
rockclimber

Reputation: 50

How to detect mouse placement in java

I have been having issues with using the MouseInfo class in Java Applets.

int somex = MouseInfo.getPointerInfo().getLocation().x;         
int somey = MouseInfo.getPointerInfo().getLocation().y;`

The above code works just fine when in a normal java program, but in an applet, I get a

Exception in thread "AWT-EventQueue-1" java.security.AccessControlException: access denied (java.awt.AWTPermission watchMousePointer)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
    at java.security.AccessController.checkPermission(AccessController.java:546)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
    at java.awt.MouseInfo.getPointerInfo(MouseInfo.java:62)
    at Mousefollow.getCOOR(Mousefollow.java:208)
    at Mousefollow.paint(Mousefollow.java:160)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:796)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:713)
    at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:693)
    etc etc etc.

Does anyone know why I cannot use that code in an applet? How do I change the security manager so this will work?

The reason that I ask this is that I have a large applet (game) which works great, except for the fact that I need to add in the mouse controls.

If anyone has a suggestion on how to adapt the above code, or an entirely different way to find the position of the mouse/keyboard, it would be appreciated.

It works relatively by using KeyListener, MouseListener, MouseMotionListener, ActionListener and such, but the problem with MouseMotion is that if the mouse is held still, it cannot detect the position of the mouse.

Upvotes: 0

Views: 308

Answers (1)

mercutio
mercutio

Reputation: 1066

Applets are not normal applications. See the doc What Applets Can and Cannot Do on the Java Tutorial. I would suggest you track the mouse cursor in your game with a MouseMotionListener.

Just save the last known position in a variable so you can detect the position when the user is not moving the mouse.

If you want your applet to behave more like a proper application you will need to sign it: See Security in Rich Internet Applications on the Java Tutorial.

Upvotes: 1

Related Questions