Steps For Handling Events In JAVA

1. Create a class which extends Applet and implements interface.

class<name> extends Applets implements <interface>

Class Skey extends Applet implements MouseListener

There are different Interfaces for different events i.e.for keyboard->KeyListner, for Mouse->MouseListner/MouseMotionListner etc.

2. Initialize applet by init method.

init() { }

3. Add or Register the listener to source for receiving notification. Each type of events has its own listener .

  1. add TypeListener(TypeListener);  
  2. addMouseListener(this);  
4. Implement the method to receive and process these notifications.
  1. public void method (eventclass obj){ }  
  2. public void mouseEntered(MouseEvent m){ }  
  3. public void mousePressed(MouseEvent m){ }  
  4. public void mouseClicked(MouseEvent m){ }  
  5. public void mouseExited(MouseEvent m){ }  
  6. public void mouseReleased(MouseEvent m){ }  
Components of Event Handling are the following:

 

  • Event Source: ex.Button,CheckBox
  • EventListener Interface: MouseListener
  • Event classes: Mouse Event
  • Methods of EventListener Interface: mouseEntered(),mousePressed(),mouseReleased(),mouseExited(),mouseClicked()

Ex.Program:

  1. package proj2;  
  2. import java.awt.*;  
  3. import java.applet.*;  
  4. import java.awt.event.*;  
  5. public class One extends Applet implements MouseListener //step 1  
  6. {  
  7.     String message = " ";  
  8.     int mouseX = 0;  
  9.     int mouseY = 0;  
  10.     public void init() //step 2  
  11.         {  
  12.             addMouseListener(this); //step3  
  13.         }  
  14.     public void mouseEntered(MouseEvent m) //step4  
  15.         {  
  16.             mouseX = m.getX();  
  17.             mouseY = m.getY();  
  18.             repaint();  
  19.         }  
  20.     public void mouseExited(MouseEvent m) {  
  21.         mouseX = m.getX();  
  22.         mouseY = m.getY();  
  23.         repaint();  
  24.     }  
  25.     public void mouseClicked(MouseEvent m) {  
  26.         message = "Mouse Clicked at :";  
  27.         mouseX = m.getX();  
  28.         mouseY = m.getY();  
  29.         repaint();  
  30.     }  
  31.     public void mousePressed(MouseEvent m) {  
  32.         message = "Mouse button is pressed at :";  
  33.         mouseX = m.getX();  
  34.         mouseY = m.getY();  
  35.         repaint();  
  36.     }  
  37.     public void mouseReleased(MouseEvent m) {  
  38.         message = " mouse released";  
  39.         mouseX = m.getX();  
  40.         mouseY = m.getY();  
  41.         repaint();  
  42.     }  
  43.     public void paint(Graphics g) {  
  44.         g.drawString(message, mouseX, mouseY);  
  45.     }  
  46. }  
Ebook Download
View all
Learn
View all