0% found this document useful (0 votes)
15 views20 pages

Module5Java

Module 5 covers Event Handling in Java, explaining the Delegation Event Model which separates event generation from processing, allowing for efficient event management. It discusses event sources, listeners, and various event classes, particularly focusing on mouse events and their handling through interfaces like MouseListener and MouseMotionListener. Additionally, the module highlights the importance of the Abstract Window Toolkit (AWT) in Java's GUI framework, despite the prevalence of more advanced frameworks like Swing.

Uploaded by

mbabsprof
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views20 pages

Module5Java

Module 5 covers Event Handling in Java, explaining the Delegation Event Model which separates event generation from processing, allowing for efficient event management. It discusses event sources, listeners, and various event classes, particularly focusing on mouse events and their handling through interfaces like MouseListener and MouseMotionListener. Additionally, the module highlights the importance of the Abstract Window Toolkit (AWT) in Java's GUI framework, despite the prevalence of more advanced frameworks like Swing.

Uploaded by

mbabsprof
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

OOPS with Java Notes(MMC202) Module 5

Module-5
Event Handling
Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism have the code which is known as
event handler that is executed when an event occurs. Java Uses the Delegation
Event Model to handle the events. This model defines the standard mechanism to
generate and handle the events.
Events are supported by a number of packages, including java.util, java.awt, and
java.awt.event. Beginning with JDK 9, java.awt and java.awt.event are part of the
java.desktop module, and java.util is part of the java.base module. Abstract
Window Toolkit (AWT) was Java’s first GUI framework and it offers a simple way
to present the basics of event handling. 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.

5.1 Two Event Handling Mechanisms


The way in which events are handled changed significantly between the original
version of Java (1.0) and all subsequent versions of Java, beginning with version
1.1. Although the 1.0 method of event handling is still supported, it is not
recommended for new programs. Also, many of the methods that support the old
1.0 event model have been deprecated. The modern approach is the way that
events should be handled by all new programs.

5.2 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
Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 1
OOPS with Java Notes(MMC202) Module 5

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 original 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.

5.3 Events
In the delegation model, an event is an object that describes a state change in a
source. Among other causes, an event 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 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. You are free to
define events that are appropriate for your application.

5.4 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

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 2
OOPS with Java Notes(MMC202) Module 5

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.
Some sources may allow only one listener to register. The general form of such a
method is this:
public void addTypeListener(TypeListener el ) throws java.util.TooManyListenersException

When such an event occurs, the registered listener is notified. This is known as
unicasting the event.

A source must also provide a method that allows a listener to unregister an


interest in a specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el )

Here, Type is the name of the event, and el is a reference to the event listener.
For example, to remove a keyboard listener, you would call removeKeyListener( ).

The methods that add or remove listeners are provided by the source that
generates events. For example, Component, which is a top-level class defined by
the AWT, provides methods to add and remove keyboard and mouse event
listeners.

5.5 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. In other words, the listener
must supply the event handlers. The methods that receive and process events are
defined in a set of interfaces, such as those 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 handle one or both of
these events if it provides an implementation of this interface.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 3
OOPS with Java Notes(MMC202) Module 5

5.6 Event Classes


The classes that represent events are at the core of Java’s event handling
mechanism. Thus, a discussion of event handling must begin with the event
classes. It is important to understand, however, that Java defines several types of
events. The most widely used events are those defined by the AWT and those
defined by Swing.

At the root of the Java event class hierarchy is EventObject, which is in java.util. It
is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)

Here, src is the object that generates this event.

EventObject defines two methods: getSource( ) and toString( ). The getSource( )


method returns the source of the event. Its general form is shown here:
Object getSource( )

As expected, toString( ) returns the string equivalent of the 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. The signature of this method is shown here: int
getID( ) Typically, you won’t use the features defined by AWTEvent directly.
Rather, you will use its subclasses. At this point, it is important to know only that
all of the other classes discussed in this section are subclasses of AWTEvent.

To summarize:

• EventObject is a superclass of all events.

• AWTEvent is a superclass of all AWT events that are handled by the delegation
event model.

The package java.awt.event defines many types of events that are generated by
various user interface elements. Table shows several commonly used event

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 4
OOPS with Java Notes(MMC202) Module 5

classes and provides a brief description of when they are generated. Commonly
used constructors and methods in each class are described in the following
sections.

5.7 The MouseEvent Class


There are eight types of mouse events. The MouseEvent class defines the
following integer constants that can be used to identify them:

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 5
OOPS with Java Notes(MMC202) Module 5

MouseEvent is a subclass of InputEvent. Here is one of its constructors:


MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean
triggersPopup)
Here, src is a reference to the component that generated the event. The type of
the event is specified by type. The system time at which the mouse event
occurred is passed in when. The modifiers argument indicates which modifiers
were pressed when a mouse event occurred. The coordinates of the mouse are
passed in x and y. The click count is passed in clicks. The triggersPopup flag
indicates if this event causes a pop-up menu to appear on this platform.
Two commonly used methods in this class are getX( ) and getY( ). These return the
X and Y coordinates of the mouse within the component when the event
occurred. Their forms are shown here:
int getX( )
int getY( )
Alternatively, you can use the getPoint( ) method to obtain the coordinates of the
mouse. It is shown here:
Point getPoint( )
It returns a Point object that contains the X,Y coordinates in its integer members:
x and y.
The translatePoint( ) method changes the location of the event. Its form is shown
void translatePoint(int x, int y)
Here, the arguments x and y are added to the coordinates of the event. The
getClickCount( ) method obtains the number of mouse clicks for this event. Its
signature is shown here:
int getClickCount( )
The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear
on this platform. Its form is shown here:
boolean isPopupTrigger( )
Also available is the getButton( ) method, shown here:
int getButton( )
It returns a value that represents the button that caused the event. For most
cases, the return value will be one of these constants defined by MouseEvent:

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 6
OOPS with Java Notes(MMC202) Module 5

The NOBUTTON value indicates that no button was pressed or released. Also
available are three methods that obtain the coordinates of the mouse relative to
the screen rather than the component. They are shown here:
Point getLocationOnScreen( )
int getXOnScreen( )
int getYOnScreen( )
The getLocationOnScreen( ) method returns a Point object that contains both the
X and Y coordinate. The other two methods return the indicated coordinate.

5.8 Event Listener Interfaces-The MouseListener Interface


The delegation event model has two parts: sources and listeners. Listeners are
created by implementing one or more of the interfaces defined by the
java.awt.event package. When an event occurs, the event source invokes the
appropriate method defined by the listener and provides an event object as its
argument. Table lists several commonly used listener interfaces and provides a
brief description of the methods that they define. The following sections examine
the specific methods that are contained in each interface.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 7
OOPS with Java Notes(MMC202) Module 5

The MouseListener Interface


This interface defines five methods. If the mouse is pressed and released at the
same point, mouseClicked( ) is invoked. When the mouse enters a component,
the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called.
The mousePressed( ) and mouseReleased( ) methods are invoked when the
mouse is pressed and released, respectively. The general forms of these methods
are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)

5.9 MouseMotionListener Interface


This interface defines two methods. The mouseDragged( ) method is called
multiple times as the mouse is dragged. The mouseMoved( ) method is called
multiple times as the mouse is moved. Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)

5.10 Delegation Event Model-Handling Mouse Events


To handle mouse events, you must implement the MouseListener and the
MouseMotionListener interfaces. The following program demonstrates the
process. It displays the current coordinates of the mouse in the program’s
window. Each time a button is pressed, the phrase “Button Down” is displayed at
the location of the mouse pointer. Each time the button is released, the phrase
“Button Released” is shown. If a button is clicked, a message stating this fact is
displayed at the current mouse location. As the mouse enters or exits the
window, a message is displayed that indicates what happened. When dragging
the mouse, a * is shown, which tracks with the mouse pointer as it is dragged.
Notice that the two variables, mouseX and mouseY, store the location of the

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 8
OOPS with Java Notes(MMC202) Module 5

mouse when a mouse pressed, released, or dragged event occurs. These


coordinates are then used by paint( ) to display output at the point of these
occurrences.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 9
OOPS with Java Notes(MMC202) Module 5

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 10
OOPS with Java Notes(MMC202) Module 5

5.11 AWT: Working with Windows, Graphics and Text


The Abstract Window Toolkit (AWT) was Java’s first GUI framework, and it has
been part of Java since version 1.0. It contains numerous classes and methods
that allow you to create windows and simple controls.
It is important to state at the outset that you will seldom create GUIs based solely
on the AWT because more powerful GUI frameworks (such as Swing, described
later in this book) have been developed for Java. Despite this fact, the AWT
remains an important part of Java. To understand why, consider the following.
At the time of this writing, the framework that is most widely used is Swing.
Because Swing provides a richer, more flexible GUI framework than does the
AWT, it is easy to jump to the conclusion that the AWT is no longer relevant—
that it has been fully superseded by Swing. This assumption is, however, false.
Instead, an understanding of the AWT is still important because the AWT
underpins Swing, with many AWT classes being used either directly or indirectly
by Swing. As a result, a solid knowledge of the AWT is still required to use Swing
effectively. Also, for some types of small programs that make only minimal use of
a GUI, using the AWT may still be appropriate. Therefore, even though the AWT
constitutes Java’s oldest GUI framework, a basic working knowledge of its
fundamentals is still important today.

5.12 AWT Classes


The AWT classes are contained in the java.awt package. It is one of Java’s largest
packages. Fortunately, because it is logically organized in a top-down, hierarchical
fashion, it is easier to understand and use than you might at first believe.
Beginning with JDK 9, java.awt is part of the java.desktop module. Table 25-1 lists
some of the many AWT classes.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 11
OOPS with Java Notes(MMC202) Module 5

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 12
OOPS with Java Notes(MMC202) Module 5

5.13 Window Fundamentals


The AWT defines windows according to a class hierarchy that adds functionality
and specificity with each level. Arguably the two most important window-related
classes are Frame and Panel. Frame encapsulates a top-level window and it is
typically used to create what would be thought of as a standard application
window. Panel provides a container to which other components can be added.
(Panel is also a superclass for Applet, which has been deprecated since JDK 9.)
Much of the functionality of Frame and Panel is derived from their parent classes.
Thus, a description of the class hierarchies relating to these two classes is
fundamental to their understanding. Figure 25-1 shows the class hierarchy for
Panel and Frame. Let’s look at each of these classes now.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 13
OOPS with Java Notes(MMC202) Module 5

 Component

At the top of the AWT hierarchy is the Component class. Component is an


abstract class that encapsulates all of the attributes of a visual component. Except
for menus, all user interface elements that are displayed on the screen and that
interact with the user are subclasses of Component. It defines over a hundred
public methods that are responsible for managing events, such as mouse and
keyboard input, positioning and sizing the window, and repainting. A Component
object is responsible for remembering the current foreground and background
colors and the currently selected text font.

 Container

The Container class is a subclass of Component. It has additional methods that


allow other Component objects to be nested within it. Other Container objects
can be stored inside of a Container (since they are themselves instances of
Component). This makes for a multileveled containment system. A container is
responsible for laying out (that is, positioning) any components that it contains. It
does this through the use of various layout managers

 Panel
The Panel class is a concrete subclass of Container. A Panel may be thought of as a
recursively nestable, concrete screen component. Other components can be
added to a Panel object by its add( ) method (inherited from Container). Once
these components have been added, you can position and resize them manually
using the setLocation( ), setSize( ), setPreferredSize( ), or setBounds( ) methods
defined by Component.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 14
OOPS with Java Notes(MMC202) Module 5

 Window
The Window class creates a top-level window. A top-level window is not
contained within any other object; it sits directly on the desktop. Generally, you
won’t create Window objects directly. Instead, you will use a subclass of Window
called Frame, described next.
 Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass
of Window and has a title bar, menu bar, borders, and resizing corners. The
precise look of a Frame will differ among environments.
 Canvas
Although it is not part of the hierarchy for Panel or Frame, there is one other class
that you will find valuable: Canvas. Derived from Component, Canvas
encapsulates a blank window upon which you can draw.

5.14 Working with Frame Windows


Typically, the type of AWT-based application window you will most often create is
derived from Frame. As mentioned, it creates a standard-style, top level window
that has all of the features normally associated with an application window, such
as a close box and title.
Here are two of Frame’s constructors:
Frame( ) throws HeadlessException
Frame(String title) throws HeadlessException
The first form creates a standard window that does not contain a title. The second
form creates a window with the title specified by title. Notice that you cannot
specify the dimensions of the window. Instead, you must set the size of the
window after it has been created. A HeadlessException is thrown if an attempt is
made to create a Frame instance in an environment that does not support user
interaction.
There are several key methods you will use when working with Frame windows.
They are examined here.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 15
OOPS with Java Notes(MMC202) Module 5

Setting the Window’s Dimensions


The setSize( ) method is used to set the dimensions of the window. It is shown
here:
void setSize(int newWidth, int newHeight)
void setSize(Dimension newSize)
The new size of the window is specified by newWidth and newHeight, or by the
width and height fields of the Dimension object passed in newSize. The
dimensions are specified in terms of pixels.
The getSize( ) method is used to obtain the current size of a window. One of its
forms is shown here:
Dimension getSize( )
This method returns the current size of the window contained within the width
and height fields of a Dimension object.

Hiding and Showing a Window


After a frame window has been created, it will not be visible until you call
setVisible( ). Its signature is shown here:
void setVisible(boolean visibleFlag)
The component is visible if the argument to this method is true. Otherwise, it is
hidden.

Setting a Window’s Title


You can change the title in a frame window using setTitle( ), which has this
general form:
void setTitle(String newTitle)
Here, newTitle is the new title for the window.

Closing a Frame Window


When using a frame window, your program must remove that window from the
screen when it is closed. If it is not the top-level window of your application, this
is done by calling setVisible(false). For the main application window, you can
simply terminate the program by calling System.exit( ). To intercept a window-
close event, you must implement the windowClosing( ) method of the
WindowListener interface.
Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 16
OOPS with Java Notes(MMC202) Module 5

5.15 Introducing Graphics


The AWT includes several methods that support graphics. All graphics are drawn
relative to a window. This can be the main window of an application or a child
window. (These methods are also supported by Swing-based windows.) The origin
of each window is at the top-left corner and is 0,0. Coordinates are specified in
pixels. All output to a window takes place through a graphics context.
A graphics context is encapsulated by the Graphics class. Here are two ways in
which a graphics context can be obtained:
• It is passed to a method, such as paint( ) or update( ), as an argument.
• It is returned by the getGraphics( ) method of Component.
Among other things, the Graphics class defines a number of methods that draw
various types of objects, such as lines, rectangles, and arcs. In several cases,
objects can be drawn edge-only or filled. Objects are drawn and filled in the
currently selected color, which is black by default. When a graphics object is
drawn that exceeds the dimensions of the window, output is automatically
clipped. A sampling of the drawing methods supported by Graphics is presented
here.

Drawing Lines
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY )
drawLine( ) displays a line in the current drawing color that begins at startX, startY
and ends at endX, endY.

Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle,
respectively. They are shown here:
void drawRect(int left, int top, int width, int height)
void fillRect(int left, int top, int width, int height)
The upper-left corner of the rectangle is at left, top. The dimensions of the
rectangle are specified by width and height. To draw a rounded rectangle, use
drawRoundRect( ) or fillRoundRect( ), both shown here:
void drawRoundRect(int left, int top, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int left, int top, int width, int height, int xDiam, int yDiam)

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 17
OOPS with Java Notes(MMC202) Module 5

A rounded rectangle has rounded corners. The upper-left corner of the rectangle
is at left, top. The dimensions of the rectangle are specified by width and height.
The diameter of the rounding arc along the X axis is specified by xDiam. The
diameter of the rounding arc along the Y axis is specified by yDiam.

Drawing Ellipses and Circles


To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These
methods are shown here:
void drawOval(int left, int top, int width, int height)
void fillOval(int left, int top, int width, int height)
The ellipse is drawn within a bounding rectangle whose upper-left corner is
specified by left, top and whose width and height are specified by width and
height. To draw a circle, specify a square as the bounding rectangle.

Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:
void drawArc(int left, int top, int width, int height, int startAngle, int sweepAngle)
void fillArc(int left, int top, int width, int height, int startAngle, int sweepAngle)
The arc is bounded by the rectangle whose upper-left corner is specified by left,
top and whose width and height are specified by width and height. The arc is
drawn from startAngle through the angular distance specified by sweepAngle.
Angles are specified in degrees. Zero degrees is on the horizontal, at the three
o’clock position. The arc is drawn counterclockwise if sweepAngle is positive, and
clockwise if sweepAngle is negative. Therefore, to draw an arc from twelve
o’clock to six o’clock, the start angle would be 90 and the sweep angle 180.

Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and
fillPolygon( ), shown here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)
The polygon’s endpoints are specified by the coordinate pairs contained within
the x and y arrays. The number of points defined by these arrays is specified by

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 18
OOPS with Java Notes(MMC202) Module 5

numPoints. There are alternative forms of these methods in which the polygon is
specified by a Polygon object.
The following program demonstrates the drawing methods just described.

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 19
OOPS with Java Notes(MMC202) Module 5

Prof Shahina Begum, Asso Prof, Dept of MCA, SIET, Vijayapur Page 20

You might also like