Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

EventHandling

EventHandling

Unit Structure

12.0 Introduction
12.1 Event
12.2 Event Source
12.3 Event Classes
12.4 Event Listener
12.5 Examples
12.6 Handling Windows Events
12.7 Adapter Classes

12.0 Introduction

Writing an applet that responds to user input, introduces us to event handling. We can make our applet respond to user input by overriding event handler methods in our applet. There are a variety of event handler methods which we will see further.
Each event must return a Boolean value (true or false), indicating whether the event should be made available to other event handlers. If you've processed an event (for example, keyDown) you might record the value, and return true to show that no other handlers should receive the event. If, however, your custom edit box can't process the character, it may want to return false to signal that other components (the panel or applet in which the component is hosted) should process it.

12.1 Event:

An Event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a GUI. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with user interface. For e.g. an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed.

12.2 Event Source:

An event source is the object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source may register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Example if you click a button an ActionEvent Object is generated. The object of the ActionEvent class contains information about the event.
In addition to GUI elements, other components such as an Applet, can generate Events. For e.g. you receive key and mouse events from an Applet.
Following is the table to describe some of the Event Sources.



12.3 Event Classes

The „EventObject‟ class is at the top of the event class hierarchy. It belongs to the java.util package. While most of the other event classes are present in java.awt.event package. The getSource() method of the EventObject class returns the object that initiated the event. The getId () method returns the nature of the event. For example, if a mouse event occurs, you can find out whether the event was click, a press, a move or release from the event object.
Following is the table to describe the Event Classes.


12.4 Event Listener:

These are objects that define methods to handle certain type of events. An event source (for example a PushButton) can generate one or more type of events, and maintain a list of event listeners for each type of event. An event source can register listeners by calling addXListener type of methods. For example a Button may register an object for handling ActionEvent by calling addActionListener. This object would then need to implement the listener interface corresponding to ActionEvent, which is ActionListener.

So to set up the processing of events the following tasks must be done.


I. For the GUI component (like pushbutton) associate a listener object class with the component by calling a method of type addXListener (See table below for list of methods).

II. Define this listener object. It must implement the corresponding interface. The name of interface is of type EventListener. Table below gives list of event listeners.
III. The object must define all the methods defined in the interface it is implementing. See table for the list of Event Listener methods defined in each Event Listener interface




12.5 EXAMPLES

1) Example for MouseEvents & MouseListener
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code= "mouseEvent" width=400 height=300>
</applet?
*/
public class mouseEvent extends Applet implements MouseListener, MouseMotionListener
{
public void init ()
{
addMouseListener (this);
addMouseMotionListener (this);
}
public void mouseClicked(MouseEvent e)
{
showStatus ("Mouse has been clicked at " + e.getX()+ "," + e.getY());
}
public void mouseEntered (MouseEvent e)
{
showStatus ("Mouse has been Entered at " + e.getX()+ "," + e.getY());
// For loop: to make sure mouse entered is on status bar for a few sec
for (int i= 0; i<1000000; i++);
}
public void mouseExited (MouseEvent e)
{
showStatus ("Mouse has been Exited at " + e.getX()+ "," + e.getY());
}
public void mousePressed (MouseEvent e)
{
showStatus ("Mouse pressed at " + e.getX()+ "," + e.getY());
}
public void mouseReleased (MouseEvent e)
{
showStatus ("Mouse released at " + e.getX()+ "," + e.getY());
}
public void mouseDragged (MouseEvent e)
{
showStatus ("Mouse dragged at " + e.getX()+ "," + e.getY());
}
public void mouseMoved(MouseEvent e)
{
showStatus ("Mouse moved at " + e.getX()+ "," + e.getY());
}
//public void paint(Graphics g)
// {
//g.drawString(msg, e.getX(), e.getY());
// }
}


  • Save the file as mouseEvent. Java 
  • Compile the file using javac mouseEvent.java 
  • On successful compilation, execute the file using appletviewer mouseEvent.java

The output appers as shown in following figure :


2) Example for Key events and KeyListener.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="keyTest" width =400 height=300>
</applet>
*/
public class keyTest extends Applet implements KeyListener
{
public void init()
{
Label lab = new Label ("Enter Characters :");
add (lab);
TextField tf = new TextField (20);
add (tf);
tf.addKeyListener(this);
}
public void keyPressed(KeyEvent e)
{
showStatus("key Down");
}
public void keyReleased(KeyEvent e)
{
showStatus("key Up");
}
public void keyTyped(KeyEvent e)
{
showStatus(" Recently typed characters are : " + e.getKeyChar());
}
}


  • Save the file as keyTest. Java 
  • Compile the file using javac keyTest.java 
  • On successful compilation, execute the file using appletviewer keyTest.java

The output appers as shown in following figure :


3) Example for Button Event and Action Listener

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/*
<applet code = "ButtonEvent" height = 400 width = 400>
</applet>
*/
public class ButtonEvent extends Applet implements ActionListener
{
Button b;
public void init()
{
b = new Button("Click me");
b.addActionListener(this);
add (b);
}
public void actionPerformed (ActionEvent e)
{
// If the target of the event was our //Button
// In this example, the check is not
// Truly necessary as we only listen//to
// A single button
if(e.getSource () == b)
{
getGraphics().drawString("OUCH Buddy",20,20);
}
}
}


  • Save the file as ButtonEvent. Java 
  • Compile the file using javac ButtonEvent.java 
  • On successful compilation, execute the file using appletviewer ButtonEvent.java

The output appers as shown in following figure :



12.6 Handling Windows Events:

When you use interfaces for creating listeners, the listener class has to override all the methods that are declared in the interface. Some of the interfaces have only one method, whereas others(windowListener) have many. So even if you want to handle only a single event, you have to override all the methods. To overcome this, the event packages provide seven adapter classes, which we will see shortly. Now coming back to handle window-related events, you need to register the listener object that implements the windowListener interface. The WindowListener interface contains a set of methods that are used to handle window events.


4) Example for Window Events

import java.awt.*;
import java.awt.event.*;
Class OurWindowListener implements windowListener
{
//Event handler for the window closing event
public void windowClosing (windowEvent we)
{
System.exit(0);
}
public void windowClosed (windowEvent we)
{
}
public void windowOpened (windowEvent we)
{
}
public void windowActivated (windowEvent we)
{
}
public void windowDeactivated (windowEvent we)
{
}
public void windowIconified (windowEvent we)
{
}
public void windowDeiconified (windowEvent we)
{
}
}
public class MyFrame extends Frame
{
Button b1;
// Main Method
public static void main (String arg[])
{
MyFrame f = new MyFrame();
}
//Constructor for the event derived class
public MyFrame()
{
Super (―Windows Events-Title‖);
b1 = new button(―Click Me‖);
//place the button object on the window
add(―center‖,b1);
//Register the listener for the button
ButtonListener listen = new ButtonListener();
b1.addActionListener(listen);
//Register a listener for the window.
OurWindowListener wlisten = new OurWindowListener();
addWindowListener(wlisten);
//display the window in a specific size
setVisible(true);
setSize(200,200);
}//end of frame class
//The Listener Class
Class ButtonListener implements ActionListener
{
//Definition for ActionPerformed() method
public void ActionPerformed(ActionEvent evt)
{
Button source = (Button)evt.getSource();
Source.setLabel(―Button Clicked, Buddy!‖);
}
}
}
In the above example MyFrame class makes a call to the addWindowListener() method, which registers object for the window. This enables the application to handle all the window-related events. When the user interacts with the application by clicking close button, maximizing or minimizing a WindowEvent object is created and delegated to the pre-registered listener of the window. Subsequently the designated event-handler is called.
In the above example, the class OurWindowListener has methods that do not contain any code. This is because the windowListener interface contains declarations for all these methods forcing you to override them.

12.7 Adapter Classes:

Java provides us with adapter classes that implement the corresponding listener interfaces containing one or more methods. The methods in these classes are empty. The Listener class that you define can extend the Adapter class and override the methods that you need. The adapter class used for WindowListener interface is the WindowAdapter class.
So you can simplify the above code (example 2) using Adapter class in the following manner:
Example :Save as MyFrames.java and complie.
import java.awt.*;
import java.awt.event.*;
Class MyFrames extends frame
{
public static void main(String arg[])
{
MyFrames f = new MyFrames();
}
//constructor of the Frame derived class
public MyFrames
{
//Register the Listener for the window
super(―The Window Adapter Sample‖);
MyWindowListener mlisten = new MyWindowListener();
addWindowListener(mlisten);
setVisible(true);
}
}
Class MyWindowListener extends WindowAdapter
{
//event handler for windows closing event
public void windowClosing(WindowEvent we)
{
MyFrames f;
f = (MyFrames)we.getSource();
f.dispose();
System.exit(0);
}
}
The Following is a list of Adapter classes and Listener Interfaces In Java:

{mospagebreak title=Dissecting Java As Far As Inner Classes} Inner Classes:


Inner classes are classes that are declared within other classes. They are also knows as nested classes and provide additional clarity to the program. The scope of the inner class is limited to the class that encloses it. The object of the inner class can access the members of the outer class. While the outer class can access the members of the inner class through an object of the inner class.

Syntax:
class
{
class
{
}
//other attributes and methods
}
Example: Save as MyFrame.java then compile and excute the program.
import java.awt.*;
import java.awt.event.*;
Class MyFrame extends Frame
{
//inner class declaration
class MyWindowListener extends MyAdapter
{
//event handler for windows closing event
public void windowClosing(WindowEvent w)
{
MyFrame frm;
frm = (MyFrames)w.getSource();
frm.dispose();
System.exit(0);
}
public static void main(String arg[])
{
MyFrame frm = new MyFrame();
}
//constructor of the Frame class
public MyFrames
{
//Register the Listener for the window
super(―Illustration For Inner or Nested Classes‖);
//creating an object of inner class
MyWindowListener wlisten = new MyWindowListener();
addWindowListener(wlisten);
setVisible(true);
setSize(100,100);
}
}
The above example code declares an object of the inner class in the constructor of an outer class. To create an object of the inner class from an unrelated class, you can use the new operator as if it were a member of the outer class.
Example:
MyFrame frame = new MyFrame(―Title‖);
Frame.MyWindowsListener listen = new MyFrame().MyWindowListener();
You can create a class inside a method. The methods of the inner class can have access to the variables define in the method containing them. Inner class must be declared after the declaration of the variables of the method so those variables are accessible to the inner class.
Example : Save As RadioTest.java, Compile And View Using Appletviewer
In this Applet example we examine MouseAdapters, and its methods like mouseClicked(). Plus ItemListener interface implementation and itemStateChanged() method and use getItem() method to display the item the user as selected in the Applet‘s status bar using the showStatus()method. We will use interface components like checkbox, which are of two types-exclusive checkboxes (which means only one among the group can be selected) also called Radio Buttons. We also use non-inclusive checkboxes, which can be selected independently. The Choice class implements the pop-up menu that allows users to select items from a menu. This UI component dispalys the currently selected item with a arrow to its right.
/*
<applet code = "RadioTest.class" height = 300 width = 300 >
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RadioTest extends Applet
{
public void init()
{
CheckboxGroup cbg = new CheckboxGroup();
// Checkbox(label, specific checkgroup, checked:boolean)
Checkbox c1 = new Checkbox("Black and White",cbg,false);
Checkbox c2 = new Checkbox("Color",cbg,false);
//adding mouselistener to the corresponding
// component to trap the event
c1.addMouseListener(new check1());
c2.addMouseListener(new check2());
//adding components to the container
add(c1);
add(c2);
//To create a Choice Menu(say to list the various choices)
// a Choice Object is instantiated.
// In short-Choice() constructor creates a new choice menu
//& you add items using addITem()
Choice c = new Choice();
c.add("LG");
c.add("Onida");
c.add("BPL");
c.add("Samsung");
c.add("Philips");
c.add("Sony");
// adding ItemListener to choice then adding it to the container
c.addItemListener(new Ch());
add(c);
}
Class check1 extends MouseAdapter
{
Public void mouseClicked(MouseEvent e)
{
showStatus("You have selected Black & White TV option");
}
}
Class check2 extends MouseAdapter
{
Public void mouseClicked(MouseEvent e)
{
showStatus("You have selected Color TV option");
}
}
Class Ch implements ItemListener
{
Public void itemStateChanged(ItemEvent e)
{
String s =(String)e.getItem();
showStatus("You have selected" + s + " brand for your TV");
}
}
}



No comments:

Post a Comment