14.7 CASE STUDY: The Game of Pong

The KeyListener Interface

The implementation of the PongFrame class is shown in figure 14.33. The frame’s main task is to manage the drawing of the ball and paddle and to handle the user’s key presses. Handling keyboard events is a simple matter of implementing the KeyListener interface. This works in much the same way as the ActionListener interface, which is used to handle button clicks and other ActionEvents. Whenever a key is pressed, it generates KeyEvents, which are passed to the appropriate methods of the KeyListener interface.

There’s a bit of redundancy in the KeyListener interface in the sense that a single key press and release generates three KeyEvents: A keytyped event, when the key is pressed, a key-released event, when the key is released, and a key-pressed event, when the key is pressed and released. While it is important for some programs to be able to distinguish between a key-typed and key-released event, for this program, we will take action whenever one of the arrow keys is pressed (typed and released). Therefore, we implement the keyPressed() method as follows:

Annotation 2020-03-25 211926

Each key on the keyboard has a unique code that identifies the key. The key’s code is gotten from the KeyEvent object by means of the

Annotation 2020-03-25 212043Annotation 2020-03-25 212233

getKeyCode() method. Then it is compared with the codes for the uparrow and down-arrow keys, which are implemented as class constants, VK UP and VK DOWN, in the KeyEvent class. If either of those keys were typed, the appropriate paddle method, moveUP() or moveDown(), is called.

Note that even though we are not using the keyPressed() and keyReleased() methods in this program, it is still necessary to provide implementations for these methods in the frame. In order to implement an interface, such as the KeyListener interface, you must implement all the abstract methods in the interface. That is why we provide trivial implementations of both the keyPressed() and keyReleased() methods.