In life, you encounter events that force you to suspend other activities and respond to them immediately. In Java, events represent all activity that goes on between the user and the application. Java's Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events.
ActionEvent using the ActionListener interface: The following illustrates the usage of ActionEvent and ActionListener interface in a Classic Java Application (Example I).
//Save the file with MyEvent.java file and compile it using javac,
//once complied errors free execute it.
Import javax.swings.*;
Import java.awt.event.*;
Public class MyEvent extends JFrame
{
JButton b1;
// Main Method
Public static void main (String arg[])
{
MyEvent event = new MyEvent();
}
//Constructor for the event derived class
Public MyEvent()
{
Super(“Window Title: Event Handling”);
b1 = new Jbutton(“Click Me”);
//place the button object on the window
getContentPane().add(“center”,b1);
//Register the listener for the button
ButtonListener listen = new ButtonListener();
b1.addActionListener(listen);
//display the window in a specific size
setVisible(true);
setSize(200,200);
}
//The Listener Class
Class ButtonListener implements ActionListener
{
//Definition for ActionPerformed() method
Public void ActionPerformed(ActionEvent evt)
{
JButton source = (JButton)evt.getSource();
Source.setText(“Button Has Been Clicked, Guru!”);
}
}
}
How does the above Application work?
• The execution begins with the main method.
• An Object of the MyEvent class is created in the main method.
• Constructor of the MyEvent class is invoked.
• Super () method calls the constructor of the base class and sets the title of the window as given.
• A button object is created and placed at the center of the window.
• A Listener Object is created.
• The addActionListener() method registers the listener object for the button.
• SetVisible () method displays the window.
• The Application waits for the user to interact with it.
• When the user clicks on the button labeled “Click Me”: The “ActionEvent” event is generated. Then the ActionEvent object is created and delegated to the registered listener object for processing. The Listener object contains the actionPerformed() method which processes the ActionEvent In the actionPerformed() method, the reference to the event source is retrieved using getSource() method. The label of the button is changed to “Button has been clicked, Guru!” using setText() method.
• Tools of the Trade: Since the ButtonListener class has been declared under MyEvent class. Therefore ButtonListener class is an inner class.