Computer Science 252
Problem Solving with Java
Fall 2013, The College of Saint Rose
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.*; // some new imports for our key events import java.awt.event.KeyEvent; import java.awt.event.KeyListener; /* * 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 * Updated for The College of Saint Rose, CSC 252, Fall 2013 * * $Id: HandlingArrowKeys.java 2218 2013-10-18 14:06:39Z 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; } }