Computer Science 120
Introduction to Programming
Spring 2012, Siena College
HandlingArrowKeys Demo
A working demo of HandlingArrowKeys will appear below. Click inside the applet to interact with it.
HandlingArrowKeys BlueJ Project
Click here to download a BlueJ project for HandlingArrowKeys.
HandlingArrowKeys Source Code
The Java source code for HandlingArrowKeys is below. Click on a file name to download it.
import objectdraw.*; import java.awt.event.*; /* * Example HandlingArrowKeys. Example to show how to set up to handle * arrow key press/release events. Note that similar techniques can be * used to check other keys. * * Jim Teresco, Siena College, CSIS 120, Spring 2012 * * $Id: HandlingArrowKeys.java 1853 2012-04-21 00:02:47Z terescoj $ */ public class HandlingArrowKeys extends WindowController implements KeyListener { // text objects to help demonstrate which arrow key // is currently and was most recently pressed private Text currentPress; private Text mostRecentPress; // is a key currently down? private boolean keyDown; public void begin() { currentPress = new Text("No arrow keys pressed yet", 10, 100, canvas); mostRecentPress = new Text("No arrow keys pressed yet", 10, 200, canvas); keyDown = false; // Get ready to handle the arrow keys requestFocus(); addKeyListener(this); canvas.addKeyListener(this); } // Required by KeyListener interface, but not used here. public void keyTyped(KeyEvent e) { } // Remember that the key is no longer down. public void keyReleased(KeyEvent e) { keyDown = false; currentPress.setText("No arrow keys currently pressed."); } /** * Handle the arrow key press. * * @param e the KeyEvent to determine direction */ public void keyPressed(KeyEvent e) { if (!keyDown) { if (e.getKeyCode() == KeyEvent.VK_UP) { currentPress.setText("Up arrow key currently pressed."); mostRecentPress.setText("Up arrow key most recently pressed."); } else if (e.getKeyCode() == KeyEvent.VK_DOWN) { currentPress.setText("Down arrow key currently pressed."); mostRecentPress.setText("Down arrow key most recently pressed."); } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) { currentPress.setText("Left arrow key currently pressed."); mostRecentPress.setText("Left arrow key most recently pressed."); } else if (e.getKeyCode() == KeyEvent.VK_RIGHT ) { currentPress.setText("Right arrow key currently pressed."); mostRecentPress.setText("Right arrow key most recently pressed."); } } keyDown = true; } }