Java Program to Handle KeyBoardEvent

«
»

This is a Java program to handle KeyBoardEvent.

Problem Description

We have to write a program in Java such that it demonstrates the event actions associated with the keyboard. The program should demonstrate various keyboard events such as key typed event, key pressed event and key released event by using alphabets, digits and non aplha numeric keys.

Expected Input and Output

For handling KeyboardEvent, we can have the following 5 different sets of input and output.

advertisement

1. To test keyTyped: When a key representing an alphabet is stroked on the keyboard and it is the first entry of input field.

For example:

If the key 'h' is the stroked/typed key on the keyboard
then the expected output is "Key Typed : h"

2. To test keyTyped: When a key representing an alphabet is stroked on the keyboard after multiple entries in input field.

For example:

If the key 'o' is the last stroked/typed key on the keyboard
then the expected output is "Key Typed : o"

3. To test keyTyped: When a key representing a digit is stroked on the keyboard after multiple entries in input field.
For example:

advertisement
If the key '1' is the last stroked/typed key on the keyboard
then the expected output is "Key Typed : 1"

4. To test keyTyped: When a key representing a digit is stroked on the keyboard after multiple entries in input field.
For example:

If the key '7' is the last stroked/typed key on the keyboard
then the expected output is "Key Typed : 7"

5. To test keyPressed: When a non aplha numeric key is kept pressed on the keyboard.
For example:

If the key 'alt' is the kept pressed on the keyboard
then the expected output is "Key Pressed : 18"
Note: 18 is the unicode of the alt key.

6. To test keyReleased: When a non aplha numeric key is pressed and released on the keyboard.
For example:

advertisement
If the key 'alt' is pressed and released on the keyboard
then the expected output is "Key Released : 18"
Note: 18 is the unicode of the alt key.
Problem Solution

1. The program uses the interfaces KeyListener and ActionListener of the java.awt package.
a) The KeyListener interface has three member methods :
i) public void keyReleased(KeyEvent): This method gives the Unicode of the key released and its character equivalent if the key pressed is a letter.
ii) public void keyPressed(KeyEvent): This method gives the Unicode of the key pressed and its character equivalent if the key pressed is a letter.
iii) public void keyTyped(KeyEvent): This method gives the character equivalent of the key pressed provided it is a valid character.

b) The ActionListener interface has member method :
public void actionPerformed(ActionEvent): This method works on the click of the exit button and the functions closes the frame.

2. @Override is a keyword used to override any method on the parent class. When the sub class has any method defined in parent/super class with same name and parameters, the Override keyword is used. This overrides the function of super class and executed the function defined in the sub class.

3. Create a class that implements the two required interfaces – KeyListener and ActionListener.
4. Create a frame, two text fields for input & output and an exit button with required dimensions. After positioning the co-ordinates of the text fields and button, add them to the frame.
5. Associate KeyListener with the input text field and ActionListener with the exit button.
6. Display the frame.
7. The functions getKeyCode() and getKeyChar() give the unicode and character representation of the key pressed respectively. Use them to display the necessary message in the output text box.

Program/Source Code

Here is source code of the Java Program to handle the keyboard events. The program is successfully compiled and tested using BlueJ on Windows 10 and javac compiler on Fedora 30.

  1. /* Java Program to demonstrate the event actions associated with a keyboard */
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. class Keyboard_Event implements KeyListener,ActionListener
  6. {
  7.     static JFrame frame;
  8.     static JTextField output;
  9.     static JTextField input;
  10.     //Driver function
  11.     public static void main(String args[])
  12.     {
  13.         //Create a frame
  14.         frame=new JFrame("Keyboard Event");
  15.         frame.setBackground(Color.white);
  16.         frame.setSize(500,500);
  17.         frame.setLayout(null);
  18.         //Create a text field for output
  19.         output=new JTextField();
  20.         output.setBounds(0,0,500,50);
  21.         frame.add(output);
  22.         //Create a text field for input
  23.         input=new JTextField();
  24.         input.setBounds(0,400,500,50);
  25.         frame.add(input);
  26.         //Create an exit button
  27.         JButton exit=new JButton("Exit");
  28.         exit.setBounds(220,200,60,30);
  29.         frame.add(exit);
  30.         //Create an object of the class
  31.         Keyboard_Event obj=new Keyboard_Event();
  32.         //Associate KeyListener with input
  33.         input.addKeyListener(obj);
  34.         //Associate ActionListener with exit
  35.         exit.addActionListener(obj);
  36.         frame.setVisible(true);
  37.     }
  38.     //function to dispose the frame when exit button is clicked
  39.     @Override
  40.     public void actionPerformed(ActionEvent e)
  41.     {
  42.         frame.dispose();
  43.     }
  44.     /*function to display the unicode of key released 
  45.       and the character if it is a letter or a digit*/
  46.     @Override
  47.     public void keyReleased(KeyEvent e)
  48.     {
  49.         output.setText("");
  50.         output.setText("Key Released : "+e.getKeyCode());
  51.         if(Character.isLetter(e.getKeyChar()))
  52.             keyTyped(e);
  53.         if(Character.isDigit(e.getKeyChar()))
  54.             keyTyped(e);
  55.     }
  56.     /*function to display the unicode of key pressed 
  57.       and the character if it is a letter or a digit*/
  58.     @Override
  59.     public void keyPressed(KeyEvent e)
  60.     {
  61.         output.setText("");
  62.         output.setText("Key Pressed : "+e.getKeyCode());
  63.         if(Character.isLetter(e.getKeyChar()))
  64.             keyTyped(e);
  65.         if(Character.isDigit(e.getKeyChar()))
  66.             keyTyped(e);
  67.     }
  68.     //function to display the character of the key typed
  69.     @Override
  70.     public void keyTyped(KeyEvent e)
  71.     {
  72.         output.setText("");
  73.         output.setText("Key Typed : "+e.getKeyChar());
  74.     }
  75. }
Program Explanation

1. Input and Output are the two text fields for input of string and output of the key action respectively.
2. The program demonstrates the functions of the KeyListener interface.
a) When the key is released, the keyReleased function is called which displays the unicode of the key and if the key is a valid letter then calls the method keyTyped.
b) When the key is pressed, the keyPressed function is called which displays the unicode of the key and if the key is a valid letter then calls the method keyTyped.
c) When the key is typed, the keyTyped function is called which displays the character representation of the key pressed.

advertisement

3. The @Override keyword overrides the functions of the parent class and executes the functions of sub class.

Runtime Test Cases

Here’s the run time test cases for keyboard events.

Test case 1 – Here’s the runtime output of the key typed operation with key “h”, where “h” is first entry of the input field.
java-program-keyboard-event-key-typed-h

Test case 2 – Here’s the runtime output of the multiple entries in key typed operation by using alphabets in the input field. For example, here the entered key is “hello”, where “o” is the last entry of the input field. The program displays that the key typed is o.
java-program-keyboard-event-key-typed-o

Test case 3 – Here’s the runtime output of the multiple entries in key typed operation by using alphabets and digits in the input field. For example, here the entered key is “hello 1”, where “1” is the last entry of the input field. The program displays that the key typed is 1.
java-program-keyboard-event-key-typed-1

Test case 4 – Here’s the runtime output of the multiple entries in key typed sequence operation by using alphabets and digits in the input field. For example, here the entered key is “hello 187”, where “7” is the last entry of the input field. The program displays that the key typed is 7.
java-program-keyboard-event-key-typed-7

Test case 5 – Here’s the runtime output of the special key pressed operation with key “alt”. After pressing alt key, it displays the unicode of the alt key which is 18.
java-program-keyboard-event-key-pressed-alt

Sanfoundry Global Education & Learning Series – Java Programs.

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn