Event Handling In Java Part II

With the skills that you have developed so far from Part I of the tutorial, you can design a graphical user interface with beauty and easy. Let us refresh ourselves before we proceed, Events are method calls that Javas windowing system performs whenever any element of a user interface is manipulated.

With the skills that you have developed so far from Part I of the tutorial, you can design a graphical user interface with beauty and easy. Let us refresh ourselves before we proceed, Events are method calls that Java’s windowing system performs whenever any element of a user interface is manipulated. Java events are part of the Java AWT (Abstract Windowing Toolkit) package. An event is the way that Java communicates to you, as the programmer, and to other Java AWT components that somethinghas happened. That “something” can be an input from the user (like button or mouse clicks, keypress), changes in the system environment (a window closing, opening or window being scrolled up or down), or a host of other things that might, in some way, affect the operation of the program.

To sum it up every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. Swing components can generate many kinds of events. We have covered a wide variety of these events like action event, mouse event, and keypress event and Event-Listeners like actionListener, mouseListener, and keyListener earlier. Today we will be taking a much closer look into Explicit Event-Handling and Adapters. {mospagebreak title=Explicit-Event Handling} An alternate way to handle events is to sub class the components and override the method that receives and dispatches event. For example you can drive a class from Button class and override the processActionEvent() method. The default action of the processActionEvent() method is to dispatch the event to the event listeners.

Example1:
Class OKButton extends Button
{
       Public OKButton (String caption)
       {
           super(caption);
           //enable processing of action events
            enableEvents(AWTEvent.Action_Event_Mask);
         }

         Public void processActionEvent(ActionEvent e)
          {
               // process event, and call superclass method 
			   // as it calls actionPerformed() method
                  super.processActionEvent(action);
         }
}
A subclass can act as an event listener for itself as shown in the following code:
Class OKButton extends Button implements ActionListener
{
   Public OKButton(String caption)
   {
           super(caption);
           //add an action listener to the button
             addActionListener(this);
    }
    Public void actionPerformed(ActionEvent ae)
   {
         // code to process event
    }
}
{mospagebreak title=Open The Window And Inhale Java In The Air} 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.

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)
In the next section we will write a sample applet so that it includes the code for window event handling.{mospagebreak title=Easy Steps For Coding} Example 2: Save as MyFrame.java.

• Create a separate listener class that implements the windowListener interface.

• Since WindowListener is an interface, you will have to define all the methods that are declared in it.

• Add the code for the specific event that you want your program to handle.

• Register the listener object for the window using the addWindowListener() method.

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 2, 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. Java’s Adapter classes provide a handy solution to this problem. {mospagebreak title=A Glimpse Of Adapters In Java} 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 3: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:
Event Category Interface Name Adapter Name Method
Window             Window Listener       Window Adapter       Void windowClosing (WindowEvent e)
Void windowOpened (WindowEvent e)
Void windowActivated (WindowEvent e)
Void windowDeactivated (WindowEvent e)
Void windowClosed (WindowEvent e)
Void windowIconified (WindowEvent e)
Void windowDeiconified (WindowEvent e)
Action ActionListener   Void actionPerformed(ActionEvent e)
Item ItemListener   Void itemStateChanged(ItemEvent e)
Mouse Motion  MouseMotionListener  MouseMotionAdapter  Void mouseDragged(MouseEvent e)
Void mouseMoved(MouseEvent e)
Mouse Button     MouseListener      MouseAdapter     Void mousePressed(MouseEvent e)
Void mouseReleased(MouseEvent e)
Void mouseEntered(MouseEvent e)
Void mouseClicked(MouseEvent e)
Void mouseExited(MouseEvent e)
Key   KeyListener   KeyAdapter   Void keyPressed(KeyEvent e)
Void keyReleased(KeyEvent e)
Void keyTyped(KeyEvent e)
Focus  FocusListener     Void focusGained(FocusEvent e)
Void focusLost(FocusEvent e)
Component    ComponentListener    ComponentAdapter    Void componentMoved(ComponentEvent e)
Void componentResized(ComponentEvent e)
Void componentHidden(ComponentEvent e)
Void componentShown(ComponentEvent e)
{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: 4 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:5
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.

Now that we have seen elaborately on Java’s Event-Handling and Adapter Classes and Inner Classes let us play with a few examples to help you understand better and see if we got a feel of everything we learned today. Don’t panic we take it each step at a time. {mospagebreak title=Preparing to Launch Our Java Applet And Handle Events} Example 6: 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”);
	      }
	}
}

Hope you got a fair idea of what Event-Handling is all about. In addition, We have also dealt elaborately with Adapter classes and inner classes to help you write simplified codes on Java’s Event-Handling. If you still feel you haven’t got the groove of it, don’t worry read the article again and experiment with some codes on your own. For experience is the best teacher.

Google+ Comments

Google+ Comments