Java – Topic 29

(KeyListener)

 

 

LESSON NOTE

 

 

KEYLISTENER INTERFACE

All of the following methods must be implemented inside a class that implements the interface:

public void keyPressed(KeyEvent e)
public void keyReleased(KeyEvent e)
public void keyTyped(KeyEvent e)

Each method relates to an obvious event (key pressed, key released or key typed).  We will focus on keyPressed and keyReleased for now.

Note that the keyPressed event continuously gets triggered if you keep a key pressed down.

 

WHAT WILL THIS LOOK LIKE?

 

            public class AppletName extends Applet implements KeyListener

            {

               //data fields go here

 

               public void init()

               {

                 

                  addKeyListener(this);

   }

 

   public void paint(Graphics g)

   {…}

 

   public void keyPressed(KeyEvent e)

   {…}

   public void keyReleased(KeyEvent e)

   {…}

   public void keyTyped(KeyEvent e)

   {…}

}           

 

KEYEVENT OBJECTS

 

The KeyEvent objects are automatically created for you.  You will likely use them to find out which key was press or to find the ascii (key code) for the key that was pressed.

 

            To find out which key triggered the event, you use:

 

                        e.getKeyChar()

 

            To find out the key code of the key that triggered the event, you use:

 

                        e.getKeyCode()

 

 

EXAMPLE 1

 

Click here to see a simple applet that demonstrates the keyPressed and keyReleased events and methods.  Click here to see the source code.

 

EXAMPLE 1B

 

Click here to see the same applet as previously. However, when the keyPressed method is called, a random number is also generated.  Keeping a key down will make the numbers continuously change.  The point of this is simply to demonstrate that the keyPressed method is called more than once if you hit a key and keep it down.

 

Click here for the source code.

 

EXAMPLE 2

 

Click here to see an applet that allows you to move an object with arrow keys.  Click here to see the source code.

 

            Note: To find out the key code for any key, you can simply use the applet in Example 1.