[ Back | Previous | Next ]

Using a Keyadapter to control the keyevents on a component

Package:
java.awt.event.*
Product:
JDK
Release:
1.1.x
Related Links:
ActionEvent
KeyEvent
MouseEvent
WindowEvent
Comment:

Using an Keyadapter to control the keyevents on a window container. is part of the JDK1.1 java.awt.event package.

The initial event is brought by the keyListener attached to the component. In our example we have implemented an keyPressed() event with the windows adapter, we also have the keyTyped() and keyReleased() implementations.

 event listener
              ...
                 adapter class
                             ...

Before you can use your keysetting the component must be in focus (component.requestFocus()).

  
import akaan.pacman.*;
import java.applet.Applet; 
import java.awt.event.*;
import java.awt.*;
class GUI extends Frame {       // App.GUI is enclosed in the PacManApp 
        Label info; // accessible for status info
        public GUI () {
                setLayout( new BorderLayout () );
                setBackground( Color.black ); 
                Panel northpanel = new Panel();
                ....
                ....
                ....
                addKeyListener( new MovementAdapter() );
        }

// // // KEY HANDLING // class MovementAdapter extends KeyAdapter { /** Handle for the KeyListener interface * key control for movement */ public void keyPressed(KeyEvent ke) { int kc = ke.getKeyCode(); if (kc == ke.VK_DOWN) { // Down playfield.pacman.setMove(0); } else if (kc == ke.VK_LEFT) { // Left == West playfield.pacman.setMove(2); } else if (kc == ke.VK_UP) { // Left == West playfield.pacman.setMove(1); } else if (kc == ke.VK_RIGHT) { // Right playfield.pacman.setMove(3); } } }

} // GUI class

1