Event handling of key events in Java 1.1 (deprecated)
Be careful: This way of handling events in Java is marked as beeing 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!
Handling key events in applets works very similar to mouse event handling, I talked about in the chapter before. There is one special method for every possible event (key down, key up). You have to overwrite the corrosponding method, if you want to handle, for example, a key down - event. In this chapter we'll have a short look at these two methods. Afterwards we will change our "moving ball" applet that way, that one can change the direction of the ball movement by pressing left or right cursor key and stop ball movement by pressing the space bar. Be carefull!! An applet is only able to handle key events once you have clicked in the applet window!!!
Now we want to modify our "moving ball" - applet a little bit. The user should be able to change the direction of the ball movement by pressing the left or right cursor key. If he presses the space bar, the ball should stop its movement. To make this possible, we have to add the following lines to our applet:
public boolean keyDown (Event e, int key)
if (key == Event.LEFT)
x_speed = -1;
// user presses right cursor key
else if (key == Event.RIGHT)
x_speed = 1;
// user presses space bar (value = 32!)
else if (key == 32)
x_speed = 0;
System.out.println ("Charakter: " + (char)key + " Integer Value: " + key);
// DON'T FORGET (although it has no meaning here)
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.
Now you are able to program every essential thing used in a game. You can move objects, handle events and load sounds and images. In the next chapter we will program our first complete game (which was the first game I programmed in Java). To understand the next chapter you have to know something about classes, objects, calling methods of other classes... . And of course you have to know everything I talked about in the last chapters. By programming this game I will show you some new techniques (how to "hit" a ball, changing mouse pointer, random ball movement...) and after programming this game you should be able to program your own games. Well Ok have fun in the next chapter and now you can watch the applet you programmed in this chapter and download the source code!
Next chapterNew event handling using event listener