Apr 20, 2012

Event Handling


When the user clicks a button, types text or perform any other interface related action in your applet, an interface event occurs. Each component has a predefined set of events. When an event occurs in your applet, the applet notified and takes the appropriate action. In this case, you can find out what events – like mouse movements or button clicks – occurs as your applet runs by using the ActionListener interface.
In the java 1.0 the action() method is to handle the button clicks, but the action() method is now deprecated-obsolete. The new technique in java 1.1 and java 2 is the event delegation model.
In this event delegation model, if the event is irrelevant, it is discarded. The JDK 1.2 model is based on four components:

1. Event class
2. Event Listener
3. Explicit event Handling
4. Adapters.

The event delegation model works like this: Events are passed from source controls to listener objects. That means you will connect a listener to a button. So, when an event occurs object will “hear” it. This is accomplished by addActionListener() method.

Button1.addActionListener(this);

The this keyword refers the object you have currently in. Catch the events sent to you by overriding the actionperformed() method and adding your own version.

public void actionPerformed(ActionEvent ae)
{
}

The actionEvent object holds information about the event that occurred. Suppose you have many buttons in your applet. So, you can find which button is clicked by, using the getSource() method. This method returns the control that caused the event. The ActionListener and actionPerformed() are in java.awt.event.* package. You must first import the java.awt.event.* package for all event handling programs.

Example:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class ActionEventDemo extends Applet implements ActionListener
{
    Button b;
    public void init()
    {
        b=new Button("Click me");
        add(b);
        b.addActionListener(this);
    }
    public void actionPerformed(ActionEvent ae)
    {
        if(ae.getSource()==b)
            b.setLabel("Clicked");        
    }
}
/*
 * <applet code="ActionEventDemo.class" width=200 height=100>
 * </applet>
 */

How to Execute this Example??

d:\>  javac ActionEventDemo.java
d:\>  appletviewer ActionEventDemo.java

Output:


video



0 comments :

Post a Comment