Key
Home Up Button Checkbox CheckboxGroup Choice Key List Menu Mouse Popup Window Text

 

In order to detect "key" events (pressing a key, releasing a key), the "KeyListener" interface must be implemented.   Experiment with the applet below to see what it does.  Then proceed to understand the code that generates the applet.

You would see an applet here if your browser supported Java.

Referring to the event handling summary,  the "KeyListener" interface includes three methods: "keyPressed", "keyReleased", and "keyTyped".  Each method takes a single parameter of type "KeyEvent". 

In the example program below, the "init" method adds a key listener to the display window via the "addKeyListener" method.  The "keyPressed" method sets the background color of the display window to red if either 'r' or 'R' is pressed, to yellow if either 'y' or 'Y' is pressed, and to blue if either 'b' or 'B' is pressed.  Notice that there are two ways to determine the key pressed.  The "getKeyChar" method returns the specific character pressed.  This method is used when determining whether the background color should be set to blue.  For the other two tests, the "getKeyCode" method is used.  "getKeyCode" returns an integer representing the key pressed.  Lowercase and uppercase letters are not distinguished.  In the KeyEvent library, there are built in constants that represent all of the possible keys that can be pressed.  For example "KeyEvent.VK_Y" represents either 'y' or 'Y'.  To learn more about the methods that operate on instances of "KeyEvent", consult a more advanced reference.

Notice in the example below, that the bodies of the "keyReleased" and "keyTyped" methods are empty.  When an interface being implemented contains many methods that have empty bodies, it is sometimes more convenient to use an adapter class.  Adapter classes is a topic that is currently not covered in this tutorial.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;          
public class Example extends Applet implements KeyListener
{
	public void init()
	{		
		addKeyListener(this);
	}          
	public void keyPressed (KeyEvent evt)
	{
		int keyCode = evt.getKeyCode();          
		if (( evt.getKeyChar() == 'b' ) || ( evt.getKeyChar() == 'B'))
			setBackground(Color.blue);
		else if ( keyCode == KeyEvent.VK_Y )
			setBackground(Color.yellow);
		else if ( keyCode == KeyEvent.VK_R )
			setBackground(Color.red);          
		repaint();
	}          
	public void keyReleased (KeyEvent evt)
	{
	}          
	public void keyTyped (KeyEvent evt)
	{
	}          
	public void paint (Graphics g)
	{
		g.drawString("Press r(ed), b(lue), or y(ellow)", 50, 50);
	}
          
}