Handle mouse events

I think there is no game that doesn't "interact" with the player. In our case, as a programmer, you have two possibilities to allow the player to interact with the computer: the player has to use the mouse or the keyboard. In the next two chapters I want to tell you how to handle mouse and keyboard events in an applet. Again this is much more easier to do in an applet as in a real application programmed for example using Java Swing. Also you won't be able to use the things you will learn here about event handling in an application, because event handling is very different in applications. But every good book about Java tells you how to handle events in applications so I think it will be no problem for you to learn it by yourself if you need to.
Now I want to change our "ball movement" applet in that way, that the ball changes the direction if the user clicks on the applet.

To do this you have to implement just one method in our Main class called mouseDown. This method should look like this:

Of course you can handle other events than the mouseDown event. Java makes it possible to overwrite the following methods the same way as I did above and handle other mouse events that way. Here comes a list of the methods:

  1. Mouse click events:
    1. public boolean mouseDown (Event e, int x, int y): handles events that occur if mouse button is pressed down
    2. public boolean mouseUp (Event e, int x, int y): handles events that occur if mouse button is released again.
    3. Use the variable e.clickCount to get the number of clicks performed. That's how you can handle for example double clicks! You'll see a example for this in chapter 5 ("Our first game").
  2. Mouse movement:
    1. public boolean mouseMove (Event e, int x, int y): handles events that occur if mouse is moved over the applet
    2. public boolean mouseDrag (Event e, int x, int y): handles events that occur if mouse is moved over the applet with pressed mouse button
  3. Mouse position:
    1. public boolean mouseEnter(Event e, int x, int y): handles events that occur if mouse enters the applet
    2. public boolean mouseExit (Event e, int x, int y): handles events that occur if mouse leaves the applet

With help of the variables int x and int y you can get the coordinates where the event happend, which is very important for many games. Also you have to take care of the return statement "return true;" that has often no meaning for the funktionality of your game but is expected by the method.

Sourcecode download
Take a look at the applet

Next chapter

Handling keyboard events