Event Handling In Java

EVENT HANDLING :

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.

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.

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.

Sources Event Sources Description
Button Generates action events when the button is pressed.
Checkbox Generates item events when the check box is selected or deselected.
List Generates action events when an item is double-clicked; generates item events when an item is selected or deselected.
Choice Generates item events when the choice is changed.
MenuItem Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected.
Scrollbar Generates adjustment events when the scrollbar is manipulated.
Text components Generates text events when the user enters a character.
Window Generates window events when a window is activated, closed , deactivated, deiconified, iconified, opened, or quit.

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.

Event Class Discription
ActionEvent A semantic event which indicates that a component-defined action occurred.
AdjustmentEvent The adjustment event emitted by Adjustable objects.
ComponentEvent A low-level event which indicates that a component moved, changed size, or changed visibility (also, the root class for the other component-level events).
ContainerEvent A low-level event which indicates that a container's contents changed because a component was added or removed.
InputEvent The root event class for all component-level input events.
ItemEvent A semantic event which indicates that an item was selected or deselected.
KeyEvent An event which indicates that a keystroke occurred in a component.
MouseEvent An event which indicates that a mouse action occurred in a component.
MouseWheelEvent An event which indicates that the mouse wheel was rotated in a component.
PaintEvent The component-level paint event.
TextEvent A semantic event which indicates that an object's text changed.
WindowEvent A low-level event that indicates that a window has changed its status.

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.

  • 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).
  • 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.
  • 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
Interface Description
ActionListener Define one method to receive action events
AdjustmentListener Defines one method to receive adjustment events.
ComponentListener Defines four methods to recognize when a component is hidden, moved, resized, or shown.
ContainerListener Defines two methods to recognize when a component is added to or removed from a container.
Focus Listener Defines two methods to recognize when a component gains or loses keyboard focus.
ItemListener Defines one method to recognize when the state of an item is changes.
KeyListener Defines 3 methods to recognize when a key is pressed, released, or typed.
MouseListener Defines 5 methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released
MouseMotionListener Defines two methods to recognize when the mouse is dragged or moved.
MouseWheelListener Defines one method to recognize when mouse wheel is moved.
TextListener Defines one method to recognize when a text value changes.
WindowFocusListener Defines two methods to recognize when window gains or loses focus.
WindowListner A window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

//EXAMPLES 1) Example for MouseEvents & MouseListener

CODE/PROGRAM/EXAMPLE
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 :

mouseEvent program in java

2) Example for Key events and KeyListener.

CODE/PROGRAM/EXAMPLE
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
KeyListener event program in java

3) Example for Button Event and Action Listener

CODE/PROGRAM/EXAMPLE
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 :

Button Event and Action Listener in java

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 windowrelated 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.

Category Event Method
Windows Events The user clicks on the cross button. void windowClosing (WindowEvent e)
The window opened for the first time. void windowOpened (WindowEvent e)
The window is activated. void windowActivated (WindowEvent e)
The window is deactivated. void windowDeactivated (WindowEvent e)
The window is closed. void windowClosed (WindowEvent e)
The window is minimized void windowIconified (WindowEvent e)
The window maximized void windowDeiconified (WindowEvent e)

4) example for Window Events

CODE/PROGRAM/EXAMPLE
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 windowrelated 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.

#event_handling_in_java #event_handling_in_java_language #event_source_in_java #event_classes_in_java #event_listener_in_java #mouse_event_in_java #Key_events_and_KeyListener_in_java #Button_Event_and_Action_Listener_in_java #handling_windows_event_in_java

(New page will open, for Comment)

Not yet commented...