Question

I am writing a game in Java, and need to have mouse interaction. I was going to use MouseAdapter, but I've looked into it some, and it does not seem to have any means of determining the location of the mouse pointer without a click or action being done... What would be the recommended way of doing this?

A couple questions:

  1. Would the mouse "location" refer to the location of the mouse in relation to the bounds of the monitor, the bounds of the game, or would it be represented as movements relative to a previous location?

  2. How would one disable the mouse pointer in a windowed application? (ie. A first person shooter where the mouse movements rotates the players view rather than move a pointer) Is this possible?

Was it helpful?

Solution

Look at the MouseMotionListener. This will allow you to track mouse movements. It will give you the location of the mouse within the component that it is attached to. But if you look at SwingUtilities class there are some convenience methods to convert points to the screen or other components or the monitor.

For the cursor, you have the option to set your own bitmap for the cursor, you can look here. Or for a more recent SO answer, you can look here. So you could hide the cursor, or set it to an empty bitmap, and then intercept the mouse movements and events to control your view.

OTHER TIPS

A tutorial on mouse events is at: http://java.sun.com/docs/books/tutorial/uiswing/events/mouselistener.html

If you look here: http://java.sun.com/javase/7/docs/api/java/awt/event/MouseEvent.html

you can get the absolute location, on the screen, or coordinates relative to the component.

If there is a movement to change direction then you will need to remove the mouse listener, or you can just have some logic where the event handler will just exit, doing nothing. I think this would be better, otherwise you have to keep track of when you add and remove the listeners.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top