AWT Applet Event Handling

AWT Applet Event Handling


Posted in : Core Java Posted on : October 30, 2010 at 5:51 PM Comments : [ 0 ]

This section contains the detail about the Applet Event Handling in java.

AWT Applet Event Handling

The container class has a group of event-handling methods which Applet incorporate to handle events. For catching specific type of events, container class has methods for each type of event. In order to react an event, an applet must override the appropriate event-specific method.

Example :

In the given example, we need to import "java.awt.event." & some of it's sub classes. And also we need to import  "java.applet.Applet" because it is an Applet and need to inherit it's property.

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;


public class AWTAppletEventHandling extends Applet 
			 implements MouseListener {

    StringBuffer strBuffer;

    public void init() {
	addMouseListener(this);
	strBuffer = new StringBuffer();
        addItem("Initializing the applet ");
    }

    public void start() {
        addItem("Starting the applet ");
    }

    public void stop() {
        addItem("stopping the applet ");
    }

    public void destroy() {
        addItem("unloading the applet");
    }

    void addItem(String word) {
        System.out.println(word);
        strBuffer.append(word);
        repaint();
    }

    public void paint(Graphics g) {
	//Draw a Rectangle around the applet's display area.
        g.drawRect(0, 0, 
		   getWidth() - 1,
		   getHeight() - 1);

	//display the string inside the rectangle.
        g.drawString(strBuffer.toString(), 10, 20);
    }

   
    public void mouseEntered(MouseEvent event) {
    }
    public void mouseExited(MouseEvent event) {
    }
    public void mousePressed(MouseEvent event) {
    }
    public void mouseReleased(MouseEvent event) {
    }

    public void mouseClicked(MouseEvent event) {
	addItem("mouse clicked! ");
    }
}

After compiling the above code, we need to embed this code into Html page as :

<html>
<title>Event Handling</title>
<hr>
<applet code="AWTAppletEventHandling.class" 
width="500" height="100">
</applet>
<hr>
</html>

Output :

When you run this code on browser, it will look like :

Whenever you clicked on it using mouse, it will display message "mouse clicked!" :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics