Key Listener in Java
To learn about Adjustment and Action Listener and check the previous blogs.
Key Listener generate Key events that indicate or active when the user is typing at the
keyboard. Hence key listener class is notified whenever you change the state of
key ,because here key is the event which is listened through this listener.
To use Key Listener Import
:
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
or
import java.awt.event.*;
Declaration:
Public interface KeyListener extends EventListener
Syntax:
public class KeyExample implements KeyListener
{
//code
}
The following are the commonly used methods:
1.public abstract void keyPressed(KeyEvent e);
2.public abstract void keyReleased(KeyEvent e);
3.public abstract void keyTyped(KeyEvent e);
Method
|
Description
|
1.
keyPressed(KeyEvent e)
|
The keyPressed method
is called when a user presses down on a key.
|
2.keyReleased(KeyEvent e);
|
keyReleased method
is called when a key is released.
|
3.
keyTyped(KeyEvent e);
|
keyTyped method
is called when a character key is typed into the inputText .
|
//
program to illustrate the use of key listener.
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class ex_key implements KeyListener {
Frame f=
new Frame("listener_key");
Label
l;
TextArea
area;
ex_key()
{
l=new
Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public
void keyPressed(KeyEvent e) {
l.setText("Key Pressed");
}
public
void keyReleased(KeyEvent e) {
l.setText("Key Released");
}
public
void keyTyped(KeyEvent e) {
l.setText("Key Typed");
}
public static void main(String[] args) {
new
ex_key();
}
}
Output:
for any query feel free to comment and follow my blog to know more about these topics.
Nice
ReplyDelete