Keyboard Listener Demo
<< Loading Image Files From Your jar | Applets | Mouse Listener Demo >> The not only demonstrates how to get key presses from the user, but is helpful for figuring out which key code the arrows buttons have!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Class Keys - a Small Demonstration of the Key Listener
*
* @author Chris Thiel, OFMCap
* @version 8 May 2008
*/
public class Keys extends JApplet implements KeyListener
{
private int keyCode;
char c;
public void init()
{
this.addKeyListener(this);
}
public void paint(Graphics g)
{
// simple text displayed on applet
g.setColor(Color.white);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.black);
g.drawString("KeyListener Demo - Press a Key", 20, 20);
g.setColor(Color.blue);
g.drawString("the key char "+c+" has code "+keyCode, 20, 40);
g.setFont(new Font("Arial", Font.PLAIN, 32));
g.setColor(Color.red);
g.drawString("\""+c+"\"", 50, 100);
}
/**
* KeyListener Interface's Implementation
*/
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e)
{
keyCode=e.getKeyCode();
c=e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e) {}
}
