Event Handling in Java Fa
Event Handling in Java Fa
University of Kashmir
Assignment Work
on
Event Handling in Java
Teacher incharge:
Dr. Shifaa Basharat
1. Event-Driven Programming:
In Java, event-driven programming is a paradigm where the flow of the program is determined by events that occur
during the execution. Events can include user actions (like button clicks or keypresses), sensor outputs, or messages
from other parts of the program. Java provides a comprehensive event-handling mechanism for building interactive
and responsive applications, especially graphical user interfaces (GUIs).
Event handling is fundamental to Java programming because it is integral to the creation of applets and other types
of GUI-based programs. Any program that uses a graphical user interface, such as a Java application written for
Windows, is event driven. Thus, we cannot write these types of programs without a solid command of event
handling. Events are supported by a number of packages, including java.util, java.awt, and java.awt.event.
Most events to which our program will respond are generated when the user interacts
with a GUI-based program. They are passed to your program in a variety of ways, with the specific method
dependent upon the actual event. There are several types of events, including those generated by the mouse, the
keyboard, and various GUI controls, such as a push button, scroll bar, or check box.
Example:
import java.awt.*;
import java.awt.event.*;
public class MyGUIApp extends Frame implements ActionListener {
Button myButton;
public MyGUIApp() {
myButton = new Button("Click me");
myButton.addActionListener(this); // Registering ActionListener
add(myButton);
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myButton) {
System.out.println("Button clicked!");
}
}
public static void main(String[] args) {
new MyGUIApp();
}
}
Events:
In the delegation model, 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 graphical user interface. 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. Many other user operations could also be cited as examples. Events may also occur that
are not directly caused by interactions with a user interface.
For example, 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 Object:
An Event object in event-driven programming is an instance of a class that encapsulates information about a specific
occurrence or state change within a system. It provides details about an event, including its type, source, and any
other relevant information.
Characteristics:
1. Information Container: The Event object contains data related to a particular event, allowing developers to
access details about what happened.
2. Event Types: There are various types of Event objects corresponding to different actions or changes, such as
button clicks, mouse movements, keyboard input, etc.
3. Attributes: Common attributes in an Event object include the source of the event, the type of the event, and
additional details specific to the event type.
General Form:
In a general sense, the creation of an Event object often involves the following steps:
// Import necessary libraries
import java.awt.event.ActionEvent; // Example import for ActionEvent
// Create an instance of the Event object
ActionEvent myEvent = new ActionEvent(sourceObject, ActionEvent.ACTION_PERFORMED,
"commandString");
In this example, `ActionEvent` is the class representing an action-related event, and `myEvent` is an instance of the
Event object. The parameters passed to the `ActionEvent` constructor typically include the source object that
generated the event (`sourceObject`), the type of action performed (e.g., `ActionEvent.ACTION_PERFORMED`),
and an optional command string providing additional information about the event. It's important to note that the
actual process of creating an Event object can vary depending on the specific event type and the associated library
or framework being used. Different types of events (e.g., MouseEvent, KeyEvent) may have their own specific
constructors and attributes.
Event Sources:
A source is an 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 must 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. Here is
the general form:
Source Object:
The Source object in event-driven programming refers to a graphical user interface (GUI) component or entity that
initiates and generates events. It is the element responsible for notifying the system about user interactions or
other relevant changes.
Characteristics:
1. Examples: Source objects can be various GUI components like buttons, checkboxes, text fields, sliders, etc.
2. Library Associations: Typically, Source objects are instances of classes provided by GUI libraries such as AWT
(Abstract Window Toolkit) or Swing in Java.
3. Responsibility: The primary responsibility of the Source object is to produce events when specific actions or
changes occur within its domain.
General Form:
In a general sense, the Source object is instantiated from a specific class, and it often involves the following steps:
// Import necessary libraries
import javax.swing.JButton; // Example import for a JButton
// Create an instance of the Source object
JButton myButton = new JButton("Click me");
In this example, `JButton` is the class representing a button component, and `myButton` is an instance of the Source
object. This button can generate events, like button clicks, and serves as an example of a Source object. In more
complex applications, various GUI components can act as Source objects, each capable of generating specific types
of events.
Event Listeners:
A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been
registered with one or more sources to receive notifications about specific types of events. Second, it must
implement methods to receive and process these notifications. The methods that receive and process events are
defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines
two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process
one or both of these events if it provides an implementation of this interface. Many other listener interfaces are
discussed later in this and other chapters.
Listener object:
The Listener object in event-driven programming is a class or entity that implements specific interfaces or extends
particular classes to handle events generated by a Source object. Its role is to "listen" for events and execute
predefined actions when those events occur.
Characteristics:
1. Responsibility: Listener objects are responsible for defining and implementing methods associated with specific
events. These methods determine the behavior when the corresponding events are triggered.
2. Registration: Listener objects need to register with a Source object to receive notifications about events. This
registration establishes a connection between the Source and the Listener.
3. Interfaces or Classes: Depending on the type of events a Listener handles, it implements relevant interfaces (e.g.,
ActionListener, MouseListener) or extends adapter classes providing default implementations.
General Form:
In a general sense, a Listener object involves the following steps:
// Import necessary libraries
import java.awt.event.ActionListener; // Example import for ActionListener
import java.awt.event.ActionEvent; // Example import for ActionEvent
// Create a class implementing the relevant interface or extending an adapter class
class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// Define actions to be taken when the associated event occurs
System.out.println("Action performed!");
}
}
// Create an instance of the Listener object
ActionListener myListener = new MyActionListener();
In this example, `MyActionListener` is a class implementing the `ActionListener` interface, and it defines the
`actionPerformed()` method. An instance of this class (`myListener`) can then be registered with a Source object
(e.g., a button) to handle action events. When the associated event occurs, the `actionPerformed()` method is
executed, printing "Action performed!" to the console.
EventObject(Object src). Here, src is the object that generates this event. The class AWTEvent, defined within the
java.awt package, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT-based
events used by the delegation event model. Its getID( ) method can be used to determine the type of the event.
Sematic events are used for high-level events, to represent user interaction with a GUI component. For example,
clicking a button, selecting a menu item, selecting a checkbox, scrolling and changing text in the text field or text
area etc; hence, an ActionEvent is a semantic event.
Low-level events are those events that make this possible. In the case of a button click, this is a mouse down, a
series of mouse moves, and a mouse up. In other words, clicking on a button is actually a sequence of mouse
movements to position the cursor followed by pressing and releasing a mouse button. Similarly, adjusting a scrollbar
is a semantic event, but dragging the mouse is a low-level event.
5. Adapter classes:
Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain
situations. An adapter class provides an empty implementation of all methods in an event listener interface. Adapter
classes are useful when you want to receive and process only some of the events that are handled by a particular
event listener interface. We can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which we are interested.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and mouseMoved( ), which are
the methods defined by the MouseMotionListener interface. If you were interested in only mouse drag events,
then you could simply extend MouseMotionAdapter and override mouseDragged( ). The empty implementation
of mouseMoved( ) would handle the mouse motion events for you.
The following example demonstrates an adapter. It displays a message in the status bar of an applet viewer or
browser when the mouse is clicked or dragged. However, all other mouse events are silently ignored. The program
has three classes. AdapterDemo extends Applet. Its init( ) method creates an instance of MyMouseAdapter and
registers that object to receive notifications of mouse events. It also creates an instance of
MyMouseMotionAdapter and registers that object to receive notifications of mouse motion events. Both of the
constructors take a reference to the applet as an argument. MyMouseAdapter extends MouseAdapter and
overrides the mouseClicked( ) method. The other mouse events are silently ignored by code inherited from the
MouseAdapter class. MyMouseMotionAdapter extends MouseMotionAdapter and overrides the
mouseDragged() method. The other mouse motion event is silently ignored by code inherited from the
MouseMotionAdapter class. Note that both of the event listener classes save a reference to the applet. This
information is provided as an argument to their constructors and is used later to invoke the showStatus( ) method.
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
As you can see by looking at the program, not having to implement all of the methods defined by the
MouseMotionListener and MouseListener interfaces saves you a considerable amount of effort and prevents your
code from becoming cluttered with empty methods. As an exercise, you might want to try rewriting one of the
keyboard input examples shown earlier so that it uses a KeyAdapter.
6. Inner Classes:
Java inner class or nested class is a class that is declared inside the class or interface. We use inner classes to logically
group classes and interfaces in one place to be more readable and maintainable. Additionally, it can access all the
members of the outer class, including private data members and methods.
The most common use of inner classes is with event handling. For example: Suppose you have a class that extends
the Frame class. Suppose now you want to use a WindowAdapter class to handle window events. Since Java does
not support multiple inheritance so your class cannot extend both the Frame and WindowAdapter class. A solution
to this problem is to define an inner class i.e. a class inside the Frame subclass that extends the WindowAdapter
class.
There is one top-level class in this program: AnonymousInnerClassDemo. The init( ) method calls the
addMouseListener( ) method. Its argument is an expression that defines and instantiates an anonymous inner class.
Let’s analyze this expression carefully. The syntax new MouseAdapter( ) { ... } indicates to the compiler that the
code between the braces defines an anonymous inner class. Furthermore, that class extends MouseAdapter. This
new class is not named, but it is automatically instantiated when this expression is executed. Because this
anonymous inner class is defined within the scope of AnonymousInnerClassDemo, it has access to all of the
variables and methods within the scope of that class. Therefore, it can call the showStatus( ) method directly. As
just illustrated, both named and anonymous inner classes solve some annoying problems in a simple yet effective
way. They also allow you to create more efficient code.
4. Checkbox (`Checkbox`): A box that users can check or uncheck to represent binary choices.
Syntax: Checkbox myCheckbox = new Checkbox("Check me");
5. Choice (`Choice`): A drop-down menu that allows users to select one item from a list of options.
Syntax: Choice myChoice = new Choice();
myChoice.add("Option 1");
myChoice.add("Option 2");
In this example, the applet includes a Button, Label, TextField, Checkbox, and Choice. Each GUI element is created
and added to the applet for display.