KeyListener Applet
KeyListener is generally used with Text related components like TextField, TextArea, etc.
KeyListener Interface
As per the event delegation model we are going to implement this interface in our class. KeyListener consists of 3 methods which are as below.
- public void keyPressed(KeyEvent e)
- public void keyReleased(KeyEvent e)
- public void keyTyped(KeyEvent e)
To add KeyListener on any component/applet the syntax is: textObj.addKeyListener(this);
For further reference you can refer my article on Event Handling Methodologies.
Program:
import java.awt.*; import java.awt.event.*; import java.applet.*; public class AppletKeyEvents extends Applet implements KeyListener { Label l1, l2; TextField tf; TextArea ta; public void init() { l1 = new Label("Enter Text:"); l2 = new Label("Output:"); ta = new TextArea(7,50); tf = new TextField(20); tf.addKeyListener(this); add(l1); add(tf); add(l2); add(ta); } public void keyTyped ( KeyEvent e ) { ta.append("Key Typed: " + tf.getText()+"\n"); } public void keyPressed ( KeyEvent e) { ta.append ( "Key Pressed: "+ tf.getText() +"\n") ; } public void keyReleased ( KeyEvent e ) { ta.append( "Key Released: "+ tf.getText()+"\n" ) ; } } /* <applet code="AppletKeyEvents" width="500" height="300"></applet> */
Recent Comments