1. Java AWT event handling involves event sources, event classes, and event listeners.
2. Event sources are AWT components like buttons and text fields that can generate events.
3. Event classes represent the specific events generated by sources, like ActionEvent for buttons.
4. Event listeners handle the events generated by sources. Listeners implement interfaces that correspond to specific event classes.
1. Java Event Handling
In AWT components, we came to know every
component (except Panel and Label) generates
events when interacted by the user like clicking over
a button or pressing enter key etc. Listeners handle
the events. Let us know the style (or design pattern)
Java follows to handle the events.
The event handling involves three types of classes.
1. Event Sources
2. Event classes
3. Event Listeners
1. Event Sources
Event sources are components, subclasses of
java.awt.Component, capable to generate events.
The event source can be a button, TextField or a
Frame etc.
java.awt.Component
After having the basic idea of Java AWT, let us know
how many component classes exist with java.awt
package.
2. 2. Event classes
Almost every event source generates an event and is
named by some Java class. For example, the button
generates ActionEvent and Checkbox generates
ItemEvent. All events listed in java.awt.event
package. Following list gives a few components and
their listeners.
3. 3. Event Listeners
The events generated by the GUI components are
handled by a special group of classes known as
"listeners". Listener is an interface. Every
component has its own listener, say,
AdjustmentListener handles the events of scrollbar
Some listeners handle the events of a few
components. For example, ActionListener handles
the events of Button, TextField, List and Menus.
Listeners are from java.awt.event package.
4. Handle Action Events for AWT Button Example
import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
5. <applet code="HandleActionEventExample"
width=200 height=200>
</applet>
*/
public class HandleActionEventExample extends
Applet implements ActionListener
{
String actionMessage="";
public void init()
{
//create Buttons
Button Button1 = new Button("Ok");
Button Button2 = new Button("Cancel");
//add Buttons
add(Button1);
add(Button2);
//set action listeners for buttons
Button1.addActionListener(this);
Button2.addActionListener(this);
}
public void paint(Graphics g)
{
g.drawString(actionMessage,10,50);