Wednesday 25 December 2013

Handle Mouse Events

Handle mouse events in Java 1.1 (deprecated)
Be careful: This way of handling events in Java is marked as being deprecated since Java 1.2 and will generate compiler warnings. But since many users still use Internet Explorer 5 which uses the JDK standard of 1.1 this way of handling events can still be used. But if you want to use an up to date event handling please read the chapter about the new event handling and use the method described there. Nevertheless this chapter here might explain some features in more detail so you might want to read it anyway
To do this you have to implement just one method in our Main class called mouseDown . This method should look like this:
// Method to handle mouse down events
public boolean mouseDown (Event e, int x, int y)
{
// Change direction
x_speed = - (x_speed);

// DON'T FORGET (although not necessary here)!!
return true;
}
Additionally to that you have to change a little bit in the run() - method to achieve the behaviour I described. Please see the source code to this chapter for details.

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:

public boolean mouseDown (Event e, int x, int y): handles events that occur if mouse button is pressed down
public boolean mouseUp (Event e, int x, int y): handles events that occur if mouse button is released again.
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").
Mouse movement:
public boolean mouseMove (Event e, int x, int y): handles events that occur if mouse is moved over the applet
public boolean mouseDrag (Event e, int x, int y): handles events that occur if mouse is moved over the applet with pressed mouse button
public boolean mouseEnter(Event e, int x, int y): handles events that occur if mouse enters the applet
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 functionality of your application .but is expected by the method.

No comments:

Post a Comment