Applet And KeyAdapter in Java

This is just a small demo of the Applet and KeyAdapter classes that Java provides for developers to handle key events. Well as we all know, Java provides listeners for handling events of a specific control. For instance for a button control it has a special listener named ActionListener, for the mouse MouseMotionListener, MouseListener etc.

All these listeners are basically interfaces in Java that provides certain methods. There are listeners that have only one method (event) whereas there are listeners that have more than one method or events. On the same grounds Java also provides Adapter classes for the developer's to write only code for those functions that they are willing to write. For instance if we implement KeListener, then the developer will need to implement all three methods, even if they only write code for one function, that's because it's an interface so we'll need to at least implement all the three functions. But this problem can be solved using adapter classes.

The following code demonstrate that.

/*

<Applet Code="KeyDemo.class" Width="350" Height="250">

</Applet>

*/

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.applet.Applet;

 

public class KeyDemo extends Applet

{

               String msg="";

               private int _x=100,_y=150;

              

               public void init()

               {

                              setBackground(Color.pink);

                              addKeyListener(new KeyAdapter()

                              {

                                             public void keyTyped(KeyEvent e)

                                             {

                                                            msg="You Pressed: ";

                                                            msg+=e.getKeyChar();

                                                            repaint();

                                             }

                              });

               }

               public void paint(Graphics g)

               {

                              g.drawString(msg,_x,_y);

               }

}

The following is the output for that.

Applet-And-KeyAdapter-in-Java.jpg

1Applet-And-KeyAdapter-in-Java.jpg

2Applet-And-KeyAdapter-in-Java.jpg

Hope you liked the article.