Keyboard and Mouse Events Handling
Keyboard and Mouse Events Handling
Keyboard and Mouse Events Handling
A user interacts with the application by pressing either keys on the keyboard or by using
mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called ‘events’. Knowing
these events will enable the programmer to write his code according to the key pressed or
mouse event.
2. Public void keyTyped(keyEvent ke) : This method is called when a key is typed on
the keyboard. This is same as keyPressed() method but this method is called when
general keys like A to Z or 1 to 9 etc are typed. It cannot work with special keys.
3. Public void keyReleased(KeyEvent ke): this method is called when a key is release.
KeyEvent class has the following methods to know which key is typed by the user.
1. Char getKeyChar(): this method returns the key name (or character) related to the key
pressed or released.
2. Int getKeyCode(): this method returns an integer number which is the value of the
key presed by the user.
The follwing are the key codes for the keys on the keyboard. They are defined as
constants in KeyEvent class. Remember VK represents Virtual Key.
To represent keys from a to z : VK_A to VK_Z.
To represent keys from 1 to 9: VK_0 to VK_9.
To represent keys from F1 to F12: VK_F1 to VK_F12.
To represent home, end : VK_HOME, VK_END.
To represent PageUp, PageDown: VK_PAGE_UP, VK_PAGE_DOWN
To represent Insert, Delete: VK_INSERT, VK_DELETE
To represent caps lock: VK_CAPS_LOCK
To represent alter key: VK_ALT
To represent Control Key: VK_CONTROL
To represent shift: VK_SHIFT
To represent tab key: VK_TAB
To represent arrow keys: VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN
To represent Escape key: VK_ESCAPE
Static String getKeyText(int keyCode); this method returns a string describing the
keyCode such as HOME, F1 or A.
Program: to trap a key which is pressed on the keyboard and display its name in the
text area.
package com.myPack;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class KeyBoardEvents extends JFrame implements KeyListener
{
private static final Font Font = null;
Container c;
JTextArea a;
Output:
Program to create a text area and display the mouse event when the button on the
mouse is clicke, when mouse is moved, etc. is done by user.
package com.myPack;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MouseEvents extends JFrame implements MouseListener, MouseMotionListener
{
String str =" ";
JTextArea ta;
Container c;
int x, y;
MouseEvents()
{
c=getContentPane();
c.setLayout(new FlowLayout());
ta.addMouseListener(this);
ta.addMouseMotionListener(this);
}
Output: