How to Listen to a Keyboard in Java
"Key listeners" in the Java programming language are triggered when you press or release a keyboard key. Keyloggers use key listeners to store the input each time the user presses a key. Programmers use key listener events to detect when a user types an incorrect character, such as by typing a letter in a text box that requires the user's phone number. Using the key listener you can alert the user to the incorrect character before he submits the form.
Instructions
-
-
1
Right-click the Java file you want to edit and select Open With. Click the Java compiler in the list of programs to load the code in the editor.
-
2
Include the listening class libraries available in Java. Copy and paste the following code to the top of your Java source code file:
import java.awt.*;
import java.awt.event.*;
-
-
3
Create the function that takes action when the user presses a key. In this example a message is sent to the Java form to display feedback for the user:
public mylistener(String key ) {
l1 = new Label ("Key Pressed!" ) ;
}
-
4
Link the key listener function to the Java form. Type the following code to add the listener to key events on your form:
addKeyListener ( this.mylistener ) ;
-
1