Event Handling In Java Part II - Easy Steps For Coding (
Page 4 of 6 )
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.