Advertisement
Method | Description |
---|---|
public char getKeyChar() | Returns the character associated with the key pressed on the keyboard, which triggered the KeyEvent. |
public int getKeyCode() | Returns an int key code associated with the key pressed on the keyboard. |
public boolean isActionKey() | Returns true if key pressed was an "action" key, i.e. keys that don't generate a character, such as Cut, Copy, Paste, Page Up, Caps Lock, the arrow and function keys. |
Method | Description |
---|---|
public void keyPressed(KeyEvent e) | This method is called when a key is pressed on the keyboard. |
public void keyReleased(KeyEvent ke) | This method is called when a key is released on the keyboard. |
public void keyTyped(KeyEvent ke) | This method is called when pressing a key on they keyboard has resulted in a character. |
Method | Description |
---|---|
public void addKeyListener(KeyListener object) | where, object is an object of the class that has implemented KeyListener interface and wanted to register itself to listen and respond to ActionEvent generated when a key is pressed in this source. |
Advertisement
import java.awt.*;
import java.awt.event.*;
public class KeyEx1 implements KeyListener
{
Label label1, label2;
TextField field1;
Frame jf;
String str;
KeyEx1()
{
jf = new Frame("Handling KeyEvent");
label1= new Label("Press any key on keyboad, to see the events it generates -", Label.CENTER);
label2= new Label();
field1 = new TextField(20); //calling TextField(String)
jf.setLayout(new FlowLayout());
jf.add(label1);
jf.add(field1);
jf.add(label2);
field1.addKeyListener(this); //As soon as button is clicked, data from all the textfields is read
jf.setSize(360,200);
jf.setVisible(true);
}
public void keyPressed(KeyEvent ke)
{
str= "KeyCode : " + ke.getKeyCode() + ", -Key Pressed- ";
label2.setText(str);
jf.setVisible(true);
}
public void keyReleased(KeyEvent ke)
{
str+=" -Key Released- ";
label2.setText(str);
jf.setVisible(true);
str="";
}
public void keyTyped(KeyEvent ke)
{
str+=" -Key Typed- ";
label2.setText(str);
jf.setVisible(true);
}
public static void main(String... ar)
{
new KeyEx1();
}
}
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement