//Purpose: This applet takes note of whenever // key is hit and if it is visible it will // change the key that is displayed. // NOTE: there is additional code here that // DOES NOT work for all Keyboards...see // API on KeyEvent and how support for the following // is not gauranteed and is keyboard-specific!!!!!! // What this other code tries to do is to monitor // when the UP, DOWN, LEFT or RIGHT arrow keys are // hit and move the position of the displayed character // UP or DOWN or to the LEFT or // RIGHT from the starting location of the // middle of the applet graphics window. // It makes sure that it does not go off the // screen!!! import java.awt.*; import java.applet.*; import java.awt.event.*; import java.awt.event.KeyListener; public class test10 extends Applet implements KeyListener { char currkey ='x'; //current character used as movable data symbol int currX; //current position of data symbol int currY; //Set background to yellow, public void init() { setBackground(Color.yellow); currX = (int) (this.size().width / 2) - 8; currY = (int) (this.size().height / 2) - 16; setFont(new Font("Helvetical", Font.BOLD, 36)); addKeyListener(this); } //key hit public void keyPressed(KeyEvent e) { System.out.println("Key is hit"); if(e.getKeyCode() == KeyEvent.VK_DOWN) currKey = 'R'; switch (e.getKeyCode() ) { case KeyEvent.VK_KP_DOWN: //THIS MAY NOT WORK ON ALL KEYBOARDS...SEE JAVA API!!! System.out.println("hi"); currY += 5; //move over 5 pixels if(currY >= this.size().height) currY = this.size().height - 1; break; case KeyEvent.VK_KP_UP: //THIS MAY NOT WORK ON ALL KEYBOARDS...SEE JAVA API!!! currY -= 5; //move over 5 pixels if(currY < 0) currY = 0; break; case KeyEvent.VK_KP_LEFT: //THIS MAY NOT WORK ON ALL KEYBOARDS...SEE JAVA API!!! currX -= 5; //move over 5 pixels if(currX < 0) currX = 0; break; case KeyEvent.VK_KP_RIGHT: //THIS MAY NOT WORK ON ALL KEYBOARDS...SEE JAVA API!!! currX += 5; //move over 5 pixels if(currX >= this.size().width) currX = this.size().width - 1; break; default: //THIS WILL WORK ON ALL KEYBOARDS currkey = e.getKeyChar(); } repaint(); return true; } //Paint the current key at the current position public void paint(Graphics g) { //set drawing color g.setColor(Color.red); if( currkey != 0){ g.drawString(String.valueOf(currkey), currX,currY); } } //Set back to center of applet window public void start() { currX = (int) (this.size().width / 2) - 8; currY = (int) (this.size().height / 2) - 16; } //Other methods need to implement KeyListener public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} }