[Go to site: main page, start]

0% found this document useful (0 votes)
11 views22 pages

Java Event Handling Explained

asvbhryikmbcxsethngfdtyiooklmnvcddseryuik,mbvcfgyuiolkjdrtyuiol,mn

Uploaded by

Chandrakala SV
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)
11 views22 pages

Java Event Handling Explained

asvbhryikmbcxsethngfdtyiooklmnvcddseryuik,mbvcfgyuiolkjdrtyuiol,mn

Uploaded by

Chandrakala SV
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

Unit-5

Event handling in java:


What is an Event?
• Change in the state of an object is known as Event, i.e., event describes the change in the state of
the source. Events are generated as a result of user interaction with the graphical user interface
components.
• For example, clicking on a button, moving the mouse, entering a character through keyboard,
selecting an item from the list, and scrolling the page are the activities that causes an event to
occur.
Types of Event
The events can be broadly classified into two categories
• Foreground Events These events require direct interaction of the user. They are generated as
consequences of a person interacting with the graphical components in the Graphical User
Interface. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page, etc.
• Background Events These events require the interaction of the end user. Operating system
interrupts, hardware or software failure, timer expiration, and operation completion are some
examples of background events.
What is Event Handling?
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has a code which is known as an 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.
The Delegation Event Model has the following key participants.
• Source: The source is an object on which the event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide us with classes for the source object.
• Listener: It is also known as event handler. The listener is responsible for generating a response
to an event. From the point of view of Java implementation, the listener is also an object. The
listener waits till it receives an event. Once the event is received, the listener processes the event
and then returns.
To perform Event Handling, we need to register the source with the listener.
Different Classes provide different registration methods.
Syntax:
addTypeListener()

where Type represents the type of event.


Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes in Java:

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.

The adjustment event is emitted by an


AdjustmentEvent AdjustmentListener
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, focusin, focusout, 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


MouseListener &
MouseEvent 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()

 componentResized()
 componentShown()
ComponentListener
 componentMoved()
 componentHidden()

 componentAdded()
ContainerListener
 componentRemoved()

 focusGained()
FocusListener
 focusLost()

ItemListener  itemStateChanged()

 keyTyped()
KeyListener  keyPressed()
 keyReleased()

 mousePressed()
 mouseClicked()
MouseListener  mouseEntered()
 mouseExited()
 mouseReleased()

 mouseMoved()
MouseMotionListener
 mouseDragged()

MouseWheelListener  mouseWheelMoved()

TextListener  textChanged()

 windowActivated()
 windowDeactivated()
 windowOpened()
WindowListener  windowClosed()
 windowClosing()
 windowIconified()
 windowDeiconified()
Flow of Event Handling
1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.

Mouse events:
This event indicates that a mouse action occurred in a component. This low-level event is
generated by a component object for Mouse Events and Mouse motion events.
This event is generated when
• A mouse button is pressed.
• A mouse button is released.
• A mouse button is clicked (pressed and released).
• A mouse cursor enters the unobscured part of component's geometry.
• A mouse cursor exits the unobscured part of component's geometry.
• A mouse is moved.
• A mouse is dragged

MouseListener and MouseMotionListener is an interface in [Link] package . Mouse


events are of two types. MouseListener handles the events when the mouse is not in motion.
While MouseMotionListener handles the events when mouse is in motion.
There are five types of events that MouseListener can generate. There are five abstract functions
that represent these five events.
The abstract functions are :
void mouseReleased(MouseEvent e) : Mouse key is released
void mouseClicked(MouseEvent e) : Mouse key is pressed/released
void mouseExited(MouseEvent e) : Mouse exited the component
void mouseEntered(MouseEvent e) : Mouse entered the component
void mousepressed(MouseEvent e) : Mouse key is pressed
There are two types of events that MouseMotionListener can generate. There are two
abstract functions that represent these five events. The abstract functions are :
void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the
component and dragged. Events are passed until the user releases the mouse button.
void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one
point to another within the component, without pressing any mouse buttons.
KEY Events:
On entering the character the Key event is generated. There are three types of key events
which are represented by the integer constants. KEY_PRESSED KEY_RELASED
KEY_TYPED.
KeyListener is an interface in [Link] package. Java KeyListener operates the
event whenever the state of the Key is changed. The class that processes the KeyEvent
implement the Java KeyListener.
Whenever the state of the key is changed, an object must be present in the program, which
helps in implementing the interface. An event will be generated by typing the key,
pressing the key, or releasing the key.
Java KeyListener interface consists of 3 Methods.

public abstract void keyPressed(KeyEvent e) It is initiated when a key has been pressed.
public abstract void keyTyped(KeyEvent e) It is initiated when a key has been typed.
public abstract void keyReleased(KeyEvent e) It is initiated when a key has been released.
Output:
GUI Basics :
• Graphical User Interface (GUI) offers user interaction via some graphical components.
For example our underlying Operating System also offers GUI via window,frame,Panel,
Button, Textfield, TextArea, Listbox, Combobox, Label, Checkbox etc. These all are
known as components or controls. Using these components we can create an interactive
user interface for an application.
• GUI provides result to end user in response to raised [Link] is entirely based
events. For example clicking over a button, closing a window, opening a window, typing
something in a textarea etc. These activities are known as [Link] makes it easier for
the end user to use an application. It also makes them interesting.
Basic Terminologies of GUI Programming
• Component: Component is an object having a graphical representation that can be
displayed on the screen and that can interact with the user. For examples buttons,
checkboxes, list and scrollbars of a graphical user interface.
•Container: Container object is a component that can contain other
[Link] added to a container are tracked in a list. The order of the list
will define the components' frontto-back stacking order within the container. If no index
is specified when adding a component to a container, it will be added to the end of the
list.
• Panel: Panel provides space in which an application can attach any other components,
including other panels.
• Window: Window is a rectangular area which is displayed on the screen. In different
window we can execute different program and display different data. Window provide us
with multitasking environment. A window must have either a frame, dialog, or another
window defined as its owner when it's constructed.
• Frame: A Frame is a top-level window with a title and a border. The size of the frame
includes any area designated for the border. Frame encapsulates window. It and has a title
bar, menu bar, borders, and resizing corners.
• GUI provides graphical icons to interact while the CUI (Character User Interface)
offers the simple text-based interfaces.
• GUI makes the application more entertaining and interesting on the other hand CUI
does not.
• GUI offers click and execute environment while in CUI every time we have to enter
the command for a task.
• New user can easily interact with graphical user interface by the visual indicators but
it is difficult in Character user interface.
• GUI offers a lot of controls of file system and the operating system while in CUI you
have to use commands which is difficult to remember.
• Windows concept in GUI allow the user to view, manipulate and control the multiple
applications at once while in CUI user can control one task at a time.
• GUI provides multitasking environment so as the CUI also does but CUI does not
provide same ease as the GUI do.
• Using GUI it is easier to control and navigate the operating system which becomes
very slow in command user interface.
GUI can be easily customized.
Examples of GUI based Applications
Following are some of the examples for GUI based applications.
• Automated Teller Machine (ATM)
• Airline Ticketing System
• Information Kiosks at railway stations
• Mobile Applications
• Navigation Systems
AWT
AWT stands for Abstract Window Toolkit. It is a platform-dependent API to develop GUI
(Graphical User Interface) or window-based applications in Java. It was developed by
heavily Sun Microsystems In 1995. It is heavy-weight in use because it is generated by
the system’s host operating system. It contains a large number of classes and methods,
which are used for creating and managing GUI.
Panels:
• The class Panel is the simplest container class.
• It provides space in which an application can attach any other component, including
other panels.
• It uses FlowLayout as default layout manager.
Class declaration
Following is the declaration for [Link] class:
public class Panel extends Container implements Accessible
Constructors
• Panel() -Creates a new panel using the default layout manager.
• Panel(LayoutManager layout) - Creates a new panel with the specified layout manager.

Method Description

Adds the specified component to this


void add(Component comp) panel.

Returns the component at the specified


Component getComponent(int n) index.

Removes the specified component from


void remove(Component comp) this panel.

Removes all components from this


void removeAll() panel.

void setLayout(LayoutManager
Sets the layout manager for this panel.
layout)

Example:
import [Link].*;
import [Link].*;

public class PanelExample {


public static void main(String[] args) {

Frame frame = new Frame("Java AWT Panel Example");


Panel panel1 = new Panel();
Panel panel2 = new Panel();
[Link](new FlowLayout());

Button button1 = new Button("Button 1");


Button button2 = new Button("Button 2");

[Link](button1);
[Link](button2);

[Link](panel1);
[Link](panel2);

[Link](400, 200);
[Link](new FlowLayout());
[Link](true);

[Link](new WindowAdapter() {
public void windowClosing(WindowEvent we) {
[Link](0);
}
});
}
}

Frame:

• The class Frame is a top level window with border and title.
• It uses BorderLayout as default layout manager.

Class declaration Following is the declaration for [Link] class


public class Frame extends Window implements MenuContainer
Layout
Layout means the arrangement of components within the container. In other way we can
say that placing the components at a particular position within the container. The task of
layouting the controls is done automatically by the Layout Manager.
Layout Manager
• The layout manager automatically positions all the components within the container. If we
do not use layout manager then also the components are positioned by the default layout
manager.
 FlowLayout: It arranges the components in a container like the words on
a page. It fills the top line from left to right and top to bottom. The
components are arranged in the order as they are added i.e. first
components appears at top left, if the container is not wide enough to
display all the components, it is wrapped around the line. Vertical and
horizontal gap between components can be controlled. The components
can be left, center or right aligned.
 BorderLayout: It arranges all the components along the edges or the
middle of the container i.e. top, bottom, right and left edges of the area.
The components added to the top or bottom gets its preferred height, but
its width will be the width of the container and also the components
added to the left or right gets its preferred width, but its height will be the
remaining height of the container. The components added to the center
gets neither its preferred height or width. It covers the remaining area of
the container.
 GridLayout: It arranges all the components in a grid of equally sized
cells, adding them from the left to right and top to bottom. Only one
component can be placed in a cell and each region of the grid will have
the same size. When the container is resized, all cells are automatically
resized. The order of placing the components in a cell is determined as
they were added.
 GridBagLayout: It is a powerful layout which arranges all the
components in a grid of cells and maintains the aspect ration of the object
whenever the container is resized. In this layout, cells may be different in
size. It assigns a consistent horizontal and vertical gap among
components. It allows us to specify a default alignment for components
within the columns or rows.
 BoxLayout: It arranges multiple components in either vertically or
horizontally, but not both. The components are arranged from left to
right or top to bottom. If the components are aligned horizontally, the
height of all components will be the same and equal to the largest sized
components. If the components are aligned vertically, the width of all
components will be the same and equal to the largest width components.
 CardLayout: It arranges two or more components having the same size.
The components are arranged in a deck, where all the cards of the same
size and the only top card are visible at any time. The first component
added in the container will be kept at the top of the deck. The default gap
at the left, right, top and bottom edges are zero and the card components
are displayed either horizontally or vertically.

Common questions

Powered by AI

Java provides several listener interfaces specifically for handling mouse events, including MouseListener, MouseMotionListener, and MouseWheelListener, each serving distinct purposes. MouseListener is used to manage non-motion events occurring with the mouse, such as button presses, clicks, and entering or exiting component geometry . On the other hand, MouseMotionListener is used to handle motion-related events like when a mouse is moved or dragged within a component's area . Lastly, MouseWheelListener is designed to handle events involving the mouse wheel being rotated, crucial for implementing scrolling functionality in UI components . Each of these interfaces includes specific methods - MouseListener, for instance, includes mousePressed and mouseClicked, while MouseMotionListener includes mouseDragged and mouseMoved - that are invoked upon corresponding mouse actions . This division of responsibilities allows for specialized handling of diverse mouse interactions, facilitating nuanced user interface behaviors.

Java's KeyListener interface is tailored specifically for managing keyboard events, distinguishing itself from other event listener interfaces by focusing on keypress actions like pressing, releasing, and typing of keys. It operates by changing the state with methods such as keyPressed, keyTyped, and keyReleased, which are invoked whenever a key is pressed down, typed, or released . Unlike other listener interfaces which might deal with multiple kinds of user interactions like mouse movements or window events, KeyListener is dedicated entirely to handling the sequence of key actions, allowing for precise control over keyboard interactions within applications. This specialization enables applications to respond immediately to keyboard inputs, which is critical for functionalities like real-time text entry and game controls . This interface's focus on keyboard state changes helps in creating responsive, keyboard-driven applications.

The Java Window class facilitates multitasking within GUI applications by serving as a fundamental container that can hold other components and execute multiple tasks simultaneously in different windows. As a non-restrictive top-level window, it is part of a multitasking environment that allows users to handle several tasks by opening several window instances. Each window instance can operate independently, providing the capability to run multiple processes, display various interfaces, and switch between tasks seamlessly . Key features of the Window class include being able to set component visibility, manage layout through layout managers, and support event handling, all of which enhance user interaction by making applications more intuitive and responsive to user actions. Additionally, its ability to hold frame, dialog, or another window as its owner during construction ensures that child windows maintain a context and order within applications, providing an organized and user-friendly multitasking experience . The Window class, through these features, significantly contributes to building comprehensive, engaging, and functional GUI applications.

Event handling in Java distinguishes between foreground and background events, impacting the way user interactions are managed. Foreground events require direct user interaction, such as clicking a button or moving the mouse, and are managed through GUI components . This type of event handling allows applications to respond immediately to user inputs, facilitating interactive user interfaces. In contrast, background events do not require direct user interaction; they might involve system interrupts or hardware failures . This separation ensures that critical non-GUI interactions are managed independently, allowing the application to handle less frequent but potentially more impactful events like system alerts or processing completions. This distinction is crucial for creating responsive and robust applications, allowing for efficient management of user-driven and system-driven events.

Using AWT for developing GUI applications in Java has significant implications, particularly concerning platform dependency and component behavior. AWT provides a set of heavyweight components that directly map to the native GUI components of the operating system, ensuring that applications appear consistent with system norms and behaviors, which can enhance user familiarity and adherence to platform standards . However, this reliance on native peers introduces platform dependency, as behavior and appearance can vary across different operating systems, potentially leading to inconsistent user experiences . Furthermore, because AWT components are heavyweight, they often require more system resources and can exhibit performance issues such as flickering or z-order problems when heavyweight and lightweight components overlap . Despite these challenges, AWT's integration of native components can simplify development for applications needing deep system integration or utilizing existing platform-specific features. Evaluating AWT's platform dependency is critical for determining its suitability for projects prioritizing cross-platform uniformity versus those seeking native optimizations.

In Java, layout managers such as FlowLayout and BorderLayout significantly impact how components are organized within a container. FlowLayout arranges components like text on a page, flowing from left to right and wrapping to the next line when space is insufficient . Components are aligned in the order they are added, with alignment options for left, center, or right, and adjustable gaps . This makes FlowLayout ideal for simple, sequential UIs where components should adapt flexibly to container resizing. In contrast, BorderLayout arranges components along the edges or center of the container, with specified regions for top, bottom, left, right, and center . Components in the top and bottom areas take their preferred height but fill the width of the container, and vice versa for left and right components. The center component fills the remaining space. This layout is used for more structured, sectional interface designs, allowing for distinct partitioning of UI elements . Both layouts offer different strategies for component placement, suited to varied interface design needs, from adaptive flows to rigidly structured arrangements.

In Java's Abstract Window Toolkit (AWT), heavyweight and lightweight components differ primarily in how they interact with system resources and rendering processes. Heavyweight components, such as AWT components, rely directly on the native system's peer, meaning they have a one-to-one mapping with native GUI objects . This results in them occupying actual screen real estate and being rendered by the system's window manager, making them dependent on the underlying operating system. Lightweight components, on the other hand, are rendered entirely in Java and do not have a native peer, resulting in less overhead and increased flexibility and portability . Heavyweight components can lead to performance inefficiencies and complex z-order stacking issues due to direct use of native painting, where overlapping components might interfere with each other. Conversely, lightweight components afford more consistent cross-platform behavior and better rendering performance by managing paint calls in Java, without direct native peer intervention. These differences are crucial when optimizing Java applications for better responsiveness and cross-platform functionality, emphasizing the performance trade-offs between heavy reliance on system calls versus purely Java-based rendering.

The Delegation Event Model is central to Java's event handling architecture, defining a systematic approach to generate and handle events. It involves key participants: the source and the listener . The source is the GUI component where the event originates, such as a button or a text field, while the listener is an object that's registered to this source to handle events . When an event occurs, the source notifies the listener (or handlers), which then processes the event and executes corresponding logic. This model decouples event generation from event handling, enabling cleaner, more modular code and allowing multiple listeners to handle events independently, enhancing flexibility and reusability of components . The Delegation Event Model thus provides a scalable way to manage interactions in complex Java applications, permitting a robust handling of user actions and system-generated events.

The FocusListener interface plays a critical role in managing focus-related events within Java applications, enabling developers to track and respond to changes in GUI component focus. This interface includes methods such as focusGained and focusLost, which are invoked when a component gains or loses focus, respectively . Handling these events is crucial for creating intuitive user interfaces where focus management is important for user experience. For instance, automatically transferring focus to a specific text field when a form loads, or validating input when focus moves away from a field, ensures that users have seamless interactions with the application. Proper focus management can also enhance accessibility and usability by allowing the application to guide user navigation through complex interfaces, ensuring that pertinent components are highlighted when needed. The FocusListener thus provides a structured way to address dynamic focus changes, contributing significantly to the robustness and user-friendliness of Java GUI applications.

You might also like