0% found this document useful (0 votes)
90 views

Event Handling in Java Fa

This document discusses event handling in Java. It provides an example of creating a basic GUI application that handles button click events. It also summarizes the key concepts of event-driven programming in Java, including the delegation event model, event objects, event sources, and event listeners.

Uploaded by

Third Party
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Event Handling in Java Fa

This document discusses event handling in Java. It provides an example of creating a basic GUI application that handles button click events. It also summarizes the key concepts of event-driven programming in Java, including the delegation event model, event objects, event sources, and event listeners.

Uploaded by

Third Party
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

PG Department of Computer Science

University of Kashmir

Assignment Work
on
Event Handling in Java

Name: Faisal Hamid


Roll No.: 22045110058
Subject: Java Programming
Class: MCA - 3rd Sem. (2022)

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();
}
}

2. Event Delegation Model or (The Delegation Event Model):


The modern approach to handling events is based on the delegation event model, which defines standard and
consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event
and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once an
event is received, the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that generates those
events. A user interface element is able to “delegate” the processing of an event to a separate piece of code. In the
delegation event model, listeners must register with a source in order to receive an event notification. This provides
an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way
to handle events than the design used by the old Java 1.0 approach. Previously, an event was propagated up the
containment hierarchy until it was handled by a component. This required components to receive events that they
did not process, and it wasted valuable time. The delegation event model eliminates this overhead. Java also allows
you to process events without using the delegation event model. This can be done by extending an AWT component.
However, the delegation event model is the preferred design for the reasons just cited.

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:

public void addTypeListener(TypeListener el)


Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that
registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener
is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and receive a copy
of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that
register to receive them.

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.

4. Examples of Listener Interfaces:


i) ActionListener: Handles action events (e.g., button clicks).
ii) MouseListener: Manages mouse-related events (e.g., clicks, movements).
iii) KeyListener: Deals with keyboard-related events.

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.

3. Methods associated with Source, Event and Listener objects.


Event Classes:
The classes that represent events are at the core of Java’s event handling mechanism. At the root of the Java
event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. It’s one constructor is
shown here:

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.

Event Classes in Java


The package java,awt.event defines many types of the events that are generated elements by various user
interfaces. The below table shows several commonly used event classes and provides a brief description of when
they are generated.
Event Class Listener Interface Description
An event that indicates that a component
ActionEvent ActionListener defined action occurred like a button click or
selecting an item from the menu item list.
AdjustmentEvent AdjustmentListener The adjustment event is emitted by an
Adjustable object like Scrollbar.
An event that indicates that a component
ComponentEvent ComponentListener moved, the size changed or changed its
visibility.
When a component is added to a container
ContainerEvent ContainerListener (or) removed from it, then this event is
generated by a container object.
These are focus-related events, which
FocusEvent FocusListener include focus, focus-in, focus-out, and blur.
An event that indicates whether an item was
ItemEvent ItemListener selected or not.
An event that occurs due to a sequence of
KeyEvent KeyListener keypresses on the keyboard.
The events that occur due to the user
MouseEvent MouseListener & interaction with the mouse (Pointing
MouseMotionListener Device).
An event that specifies that the mouse wheel
MouseWheelEvent MouseWheelListener was rotated in a component.
An event that occurs when an object’s text
TextEvent TextListener changes.
An event which indicates whether a window
WindowEvent WindowListener has changed its status or not.

Different interfaces consists of different methods which are specified below:

Listener Interface Methods


ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
FocusListener focusGained(), focusLost()
ItemListener itemStateChanged()
KeyListener keyTyped(), keyPressed(), keyReleased()
MouseListener mousePressed(), mouseClicked(), mouseEntered(),
mouseExited(), mouseReleased()
MouseMotionListener mouseMoved(), mouseDragged()
TextListener textChanged()
WindowListener windowActivated(), windowDeactivated(), windowOpened()
windowClosed(), windowClosing(), windowIconified(),
windowDeiconified()
MouseWheelListener mouseWheelMoved()
4. Low-level vs Semantic events.
The AWT makes a useful distinction between low-level and semantic events.

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.

There are four semantic event classes in the java.awt.event package:


• ActionEvent (for a button click, a menu selection, selecting a list item, or ENTER typed in a text field)
• AdjustmentEvent (the user adjusted a scroll bar)
• ItemEvent (the user made a selection from a set of checkbox or list items)
• TextEvent (the contents of a text field or text area were changed)
There are seven low-level event classes:
• ComponentEvent (the component was resized, moved, shown, or hidden); also is the base class for all low-level events
• KeyEvent (a key was pressed or released)
• MouseEvent (the mouse button was pressed, released, moved, or dragged)
• MouseWheelEvent (the mouse wheel was rotated)
• FocusEvent (a component got focus, or lost focus)
• WindowEvent (the window state changed)
• ContainerEvent (a component has been added or removed)

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.

Syntax: class Outer_Demo {


class Inner_Demo {
}
}

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.

7. Anonymous Inner classes:


An anonymous inner class is one that is not assigned a name. This section illustrates how an anonymous inner class
can facilitate the writing of event handlers. Consider the applet shown in the following listing. As before, its goal is
to display the string “Mouse Pressed” in the status bar of the applet viewer or browser when the mouse is pressed.
// Anonymous inner class demo.
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener( new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
} );
}
}

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.

8. Adding GUI elements to Applet


In Java, GUI (Graphical User Interface) elements are used to create interactive and visually appealing user interfaces.
Here are commonly used GUI elements in Java applets:

1. Button(`Button`): A clickable button that users can press to trigger an action.


Syntax: Button myButton = new Button("Click me");
2. Label (`Label`): A non-editable text component used to display information.
Syntax: Label myLabel = new Label("This is a label");

3. TextField (`TextField`): An input field that allows users to enter text.


Syntax: TextField myTextField = new TextField("Default Text");

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");

Example using these elements in Applet:


import java.applet.Applet;
import java.awt.*;
public class GUIAppletExample extends Applet {
public void init() {
// Button
Button myButton = new Button("Click me");
// Label
Label myLabel = new Label("This is a label");
// TextField
TextField myTextField = new TextField("Default Text");
// Checkbox
Checkbox myCheckbox = new Checkbox("Check me");
// Choice
Choice myChoice = new Choice();
myChoice.add("Option 1");
myChoice.add("Option 2");
// Add elements to the applet
add(myButton);
add(myLabel);
add(myTextField);
add(myCheckbox);
add(myChoice);
}
}

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.

You might also like