How to Have Java Read Keystrokes as Input

How to Have Java Read Keystrokes as Input thumbnail
It doesn't take much Java code to log a user's keystrokes.

When a Java user presses a keyboard key, Java knows the key's value. Your Java application or applet may need to know that value as well to function correctly. Java games, for example, often rely on keyboard input to control the action. Business applications might allow users to perform complex tasks using shortcut keys. Java has a built-in method that makes all keystroke values available to you. Your Java program simply needs to read those values and react accordingly.

Instructions

    • 1

      Open your JAVA editing program and create a new Java Applet file named KeyReader.

    • 2

      Paste the code shown below into that file:

      import java.awt.event.*;
      import java.awt.*;
      import java.applet.*;

      These import statements import the Java libraries needed to make your application run.

    • 3

      Paste the following code after the code listed in step two:

      public class KeyReader extends Applet {

      public void init(){
      TextField textBox = new TextField(" ");
      add(textBox);

      textBox.addKeyListener (new KeyAdapter() {
      public void keyPressed(KeyEvent e) {
      int keyCode = e.getKeyCode();
      System.out.println("You Pressed " + keyCode);
      }
      }
      );
      }
      }

      The first line of code in the init method creates a new text box you can use to test the application. The remaining lines use the addKeyListener method to create a new KeyAdapter. The keyPressed event handler runs whenever someone presses a keyboad key. The "e" event handler parameter holds all information related to a keystroke event. The keyCode variable stores the numeric value of the key pressed. The final statement displays the key you press.

    • 4

      Save your project and run it. A new Applet window opens and displays a text box. Press any key. Your Java Editing program displays the numeric key you pressed. Each key generates a unique value. The letter "a" generates 65. Zero produces 48 and pressing "F8" creates 119.

Tips & Warnings

  • After examining a key, your program can perform a variety of tasks based on the key's value. For instance, if you want to allow users to press F8 to open a menu, call a method that does that when the key they press generates a keyCode value of 119.

  • If you'd like to know the numeric values of all keys on a keyboard, visit a website that contains a cross reference table showing those values.

  • Build your own key logger Java program by storing each keyCode value that a user generates inside an array.

Related Searches:

References

Resources

  • Photo Credit Jupiterimages/Polka Dot/Getty Images

Comments

Related Ads

Featured