Monday, 9 July 2018

Handling Key Press Event in Java programming



Introduction
In this post, you will learn about the handling key press event in java programing. Key Press is the event that is generated when anyone press any key to the specific component of java. This event is performed by any the KeyListener method. When anyone press or release keys for the keyboard then key events are fired by the KeyListener objects which generates the KeyEvent environment for the component in application.
here , you will see how operations are performed when  press the key to the specific component. Here,
the KeyPress is a constructor of the main class. This constructor creates a frame and set text field to the panel.
Then the panel and the label have been set to the frame in the program. When you enter the character in the text
field through the keyboard then your entered data will be displayed in the label. some various method have
been used to do the required are given below :

getKeyChar():
This is the method of the KeyEvent class which determines the character that has been entered by you. This method returns the character associated the KeyEvent.
KeyAdapter
This is the class is used to receive the keyboard events. It creates the keyListener objects using the addKeyListener() method. The generated event is passed to every
KeyListener objects that receives such types of events using the addKeyListener() method of the object.
KeyPressed():
This method has been used in the program which receives the generated event when you press any key to the object. Above method also sets the text of the source of the
event to the label.
Here is the code of program:


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package addtwoclass;
import java.awt.*;
import java.awt.event.*;
/**
 *
 * @author rajesh kumar shukla
 */
public class KeyPress extends Frame{
Label label;
TextField txtField;
public static void main(String[] args) {
KeyPress k = new KeyPress();
}
public KeyPress(){
super("Key Press Event Frame");
Panel panel = new Panel();
label = new Label();
label.setForeground(Color.RED);
label.setFont(new java.awt.Font("Dialog", 1, 200));
txtField = new TextField(20);
txtField.addKeyListener(new MyKeyListener());
add(label, BorderLayout.NORTH);
panel.add(txtField, BorderLayout.CENTER);
add(panel, BorderLayout.CENTER);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setSize(400,400);
setVisible(true);
}
public class MyKeyListener extends KeyAdapter{
public void keyPressed(KeyEvent ke){
char i = ke.getKeyChar();
String str = Character.toString(i);
label.setText(str);
}
}
}




0 comments:

Post a Comment