Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 26

OBJECT ORIENTED STRUCTURE

(UNIT-5)
Java Servlet

Servlets are Java programs running on a web server that produce results viewed remotely on a
web server. Java Servlets "serve as platform independent, dynamically loadable, pluggable
helper bytecode objects on the server side that can be used to dynamically extend server-side
functionality

The life cycle of a servlet can be categorized into four parts:

1. Loading and Inatantiation: The servlet container loads the servlet during startup or
when the first request is made. The loading of the servlet depends on the attribute <load-
on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then
the servlet is load with loading of the container otherwise it load when the first request
comes for service. After loading of the servlet, the container creates the instances of the
servlet.
2. Initialization: After creating the instances, the servlet container calls the init() method
and passes the servlet initialization parameters to the init() method. The init() must be
called by the servlet container before the servlet can service any request. The
initialization parameters persist untill the servlet is destroyed. The init() method is called
only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the servlet
container unloads the servlet.
3. Servicing the Request: After successfully completing the initialization process, the
servlet will be available for service. Servlet creates seperate threads for each request. The
sevlet container calls the service() method for servicing any request. The service()
method determines the kind of request and calls the appropriate method (doGet() or
doPost()) for handling the request and sends response to the client using the methods of
the response object.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the
servlet container calls the destroy() method . Like the init() method this method is also
called only once throughout the life cycle of the servlet. Calling the destroy() method
indicates to the servlet container not to sent the any request for service and the servlet
releases all the resources associated with it. Java Virtual Machine claims for the memory
associated with the resources for garbage collection.

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)

Writing Servlet Hello World

We should start understanding the servlets from the beginning. Lets start by making one program
which will just print the "Hello World" on the browser. Each time the user visits this page it will
display "Hello World" to the user.

As we know that the our servlet extends the HttpServlet and overrides the doGet() method
which it inherits from the HttpServlet class. The server invokes doGet() method whenever web
server recieves the GET request from the servlet. The doGet() method takes two arguments first
is HttpServletRequest object and the second one is HttpServletResponse object and this method
throws the ServletException.

Whenever the user sends the request to the server then server generates two obects, first is
HttpServletRequest object and the second one is HttpServletResponse object.
HttpServletRequest object represents the client's request and the HttpServletResponse represents
the servlet's response.

Inside the doGet(() method our servlet has first used the setContentType() method of the
response object which sets the content type of the response to text/html. It is the standard MIME
content type for the Html pages. After that it has used the method getWriter() of the response
object to retrieve a PrintWriter object. To display the output on the browser we use the
println() method of the PrintWriter class.

The code the program is given below:


BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></head>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}

Methods of Servlets
A Generic servlet contains the following five methods:

init()

public void init(ServletConfig config) throws ServletException

The init() method is called only once by the servlet container throughout the life of a servlet. By
this init() method the servlet get to know that it has been placed into service.

The servlet cannot be put into the service if

• The init() method does not return within a fix time set by the web server.
• It throws a ServletException

Parameters - The init() method takes a ServletConfig object that contains the initialization
parameters and servlet's configuration and throws a ServletException if an exception has
occurred.

service()

public void service(ServletRequest req, ServletResponse res) throws ServletException,


IOException

Once the servlet starts getting the requests, the service() method is called by the servlet container
to respond. The servlet services the client's request with the help of two objects. These two
objects javax.servlet.ServletRequest and javax.servlet.ServletResponse are passed by the
servlet container.

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
The status code of the response always should be set for a servlet that throws or sends an error.

Parameters - The service() method takes the ServletRequest object that contains the client's
request and the object ServletResponse contains the servlet's response. The service() method
throws ServletException and IOExceptions exception.

getServletConfig()

public ServletConfig getServletConfig()

This method contains parameters for initialization and startup of the servlet and returns a
ServletConfig object. This object is then passed to the init method. When this interface is
implemented then it stores the ServletConfig object in order to return it. It is done by the
generic class which implements this inetrface.

Returns - the ServletConfig object

getServletInfo()

public String getServletInfo()

The information about the servlet is returned by this method like version, author etc. This
method returns a string which should be in the form of plain text and not any kind of markup.

Returns - a string that contains the information about the servlet

destroy()

public void destroy()

This method is called when we need to close the servlet. That is before removing a servlet
instance from service, the servlet container calls the destroy() method. Once the servlet container
calls the destroy() method, no service methods will be then called . That is after the exit of all the
threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to
clean up all the resources like memory, threads etc which are being held.

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)

Java Swing
Swing is the primary Java GUI widget toolkit. It is part of Sun Microsystems' Java Foundation
Classes (JFC) — an API for providing a graphical user interface (GUI) for Java programs.

Swing was developed to provide a more sophisticated set of GUI components than the earlier
Abstract Window Toolkit. Swing provides a native look and feel that emulates the look and feel
of several platforms, and also supports a pluggable look and feel that allows applications to have
a look and feel unrelated to the underlying platform.

The Swing Architecture


Swing is a platform-independent, Model-View-Controller GUI framework for Java. It follows a
single-threaded programming model, and possesses the following traits:

Foundations

Swing is platform independent both in terms of expression (Java) and implementation (Look-
and-Feel).

Extensible

Swing is a highly partitioned architecture, which allows for the "plugging" of various custom
implementations of specified framework interfaces: Users can provide their own custom
implementation(s) of these components to override the default implementations. In general,
Swing users can extend the framework by extending existing (framework) classes and/or
providing alternative implementations of core components.

Swing is a component-based framework. The distinction between objects and components is a


fairly subtle point: concisely, a component is a well-behaved object with a known/specified
characteristic pattern of behaviour. Swing objects asynchronously fire events, have "bound"
properties, and respond to a well-known set of commands (specific to the component.)
Specifically, Swing components are Java Beans components, compliant with the Java Beans
Component Architecture specifications...

Customizable

Given the programmatic rendering model of the Swing framework, fine control over the details
of rendering of a component is possible in Swing. As a general pattern, the visual representation
of a Swing component is a composition of a standard set of elements, such as a "border", "inset",
BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
decorations, etc. Typically, users will programmaticaly customize a standard Swing component
(such as a JTable) by assigning specific Borders, Colors, Backgrounds, opacities, etc., as the
properties of that component. The core component will then use these properties (settings) to
determine the appropriate renderers to use in painting its various aspects. However, it is also
completely possible to create unique GUI controls with highly customized visual representation.

Configurable

Swing's heavy reliance on runtime mechanisms and indirect composition patterns allows it to
respond at runtime to fundamental changes in its settings. For example, a Swing-based
application can change its look and feel at runtime. Further, users can provide their own look and
feel implementation, which allows for uniform changes in the look and feel of existing Swing
applications without any programmatic change to the application code.

Lightweight UI

Swing's configurability is a result of a choice not to use the native host OS's GUI controls for
displaying itself. Swing "paints" its controls programmatically through the use of Java 2D APIs,
rather than calling into a native user interface toolkit. Thus, a Swing component does not have a
corresponding native OS GUI component, and is free to render itself in any way that is possible
with the underlying graphics APIs.

However, at its core every Swing component relies on an AWT container, since (Swing's)
JComponent extends (AWT's) Container. This allows Swing to plug into the host OS's GUI
management framework, including the crucial device/screen mappings and user interactions,
such as key presses or mouse movements. Swing simply "transposes" its own (OS agnostic)
semantics over the underlying (OS specific) components. So, for example, every Swing
component paints its rendition on the graphic device in response to a call to component.paint(),
which is defined in (AWT) Container. But unlike AWT components, which delegated the
painting to their OS-native "heavyweight" widget, Swing components are responsible for their
own rendering.

This transposition and decoupling is not merely visual, and extends to Swing's management and
application of its own OS-independent semantics for events fired within its component
containment hierarchies. Generally speaking, the Swing Architecture delegates the task of
mapping the various flavors of OS GUI semantics onto a simple, but generalized, pattern to the
AWT container. Building on that generalized platform, it establishes its own rich and complex
GUI semantics in the form of the JComponent model.

Loosely-Coupled and MVC

The Swing library makes heavy use of the Model/View/Controller software design pattern[1],
which conceptually decouples the data being viewed from the user interface controls through
which it is viewed. Because of this, most Swing components have associated models (which are

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
specified in terms of Java interfaces), and the programmer can use various default
implementations or provide their own. The framework provides default implementations of
model interfaces for all of its concrete components. The typical use of the Swing framework does
not require the creation of custom models, as the framework provides a set of default
implementations that are transparently, by default, associated with the corresponding
JComponent child class in the Swing library. In general, only complex components, such as
tables, trees and sometimes lists, may require the custom model implementations around the
application-specific data structures. To get a good sense of the potential that the Swing
architecture makes possible, consider the hypothetical situation where custom models for tables
and lists are wrappers over DAO and/or EJB services.

Typically, Swing component model objects are responsible for providing a concise interface
defining events fired, and accessible properties for the (conceptual) data model for use by the
associated JComponent. Given that the overall MVC pattern is a loosely-coupled collaborative
object relationship pattern, the model provides the programmatic means for attaching event
listeners to the data model object. Typically, these events are model centric (ex: a "row inserted"
event in a table model) and are mapped by the JComponent specialization into a meaningful
event for the GUI component.

For example, the JTable has a model called TableModel that describes an interface for how a
table would access tabular data. A default implementation of this operates on a two-dimensional
array.

The view component of a Swing JComponent is the object used to graphically "represent" the
conceptual GUI control. A distinction of Swing, as a GUI framework, is in its reliance on
programmatically-rendered GUI controls (as opposed to the use of the native host OS's GUI
controls). Prior to Java 6 Update 10, this distinction was a source of complications when mixing
AWT controls, which use native controls, with Swing controls in a GUI (see Mixing AWT and
Swing components).

Finally, in terms of visual composition and management, Swing favors relative layouts (which
specify the positional relationships between components) as opposed to absolute layouts (which
specify the exact location and size of components). This bias towards "fluid"' visual ordering is
due to its origins in the applet operating environment that framed the design and development of
the original Java GUI toolkit. (Conceptually, this view of the layout management is quite similar
to that which informs the rendering of HTML content in browsers, and addresses the same set of
concerns that motivated the former.)

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
[edit] Relationship to AWT

AWT and Swing class hierarchy

Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided
platform-independent APIs for user interface components. In AWT, each component is rendered
and controlled by a native peer component specific to the underlying windowing system.

By contrast, Swing components are often described as lightweight because they do not require
allocation of native resources in the operating system's windowing toolkit. The AWT
components are referred to as heavyweight components.

Much of the Swing API is generally a complementary extension of the AWT rather than a direct
replacement. In fact, every Swing lightweight interface ultimately exists within an AWT
heavyweight component because all of the top-level components in Swing (JApplet, JDialog,
JFrame, and JWindow) extend an AWT top-level container. Prior to Java 6 Update 10, the use of
both lightweight and heavyweight components within the same window was generally
discouraged due to Z-order incompatibilities. However, later version of Java have fixed these
issues, and both Swing and AWT components can now be used in one GUI without Z-order
issues.

The core rendering functionality used by Swing to draw its lightweight components is provided
by Java 2D, another part of JFC.

The following is a rather simple Swing-based program. It displays a window (a JFrame)


containing a label and a button.

Notice how all instantiation and handling of all Swing components are done on the Event
Dispatch Thread by use of the method EventQueue.invokeLater(Runnable)) and an
anonymous Runnable class (see Swing and thread safety).
BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
// Import the swing and AWT classes needed
import java.awt.EventQueue;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
* Basic Swing example.
*/
public class SwingExample {
public static void main(String[] args) {

// Make sure all Swing/AWT instantiations and accesses are done on the
// Event Dispatch Thread (EDT)
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// Create a JFrame, which is a Window with "decorations", i.e.
// title, border and close-button
JFrame f = new JFrame("Swing Example Window");

// Set a simple Layout Manager that arranges the contained


// Components
f.setLayout(new FlowLayout());

// Add some Components


f.add(new JLabel("Hello, world!"));
f.add(new JButton("Press me!"));

// "Pack" the window, making it "just big enough".


f.pack();

// Set the default close operation for the window, or else the
// program won't exit when clicking close button
// (The default is HIDE_ON_CLOSE, which just makes the window
// invisible, and thus doesn't exit the app)
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

// Set the visibility as true, thereby displaying it


f.setVisible(true);
}
});
}
}

Layout Managers
BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)

• Precise layout functionality is often performed and a repetitive task. By the principles of
OOP, it should be done by classes dedicated to it. These classes are layout managers.
• Platform independence requires that we delegate the positioning and painting to layout
managers. Even then, Java does not guarantee a button will look the same in different
platforms.(w/o using Swing)
• Components are added to a container using add method. A layout manager is associated with
the container to handle the positioning and appearance of the components.
• add method is overloaded. Constraints are used differently by different layout managers.
Index can be used to add the component at a particular place. Default is –1 ( i.e. at the end)
Component add(Component comp)
Component add(Component comp, int index)
void add(Component comp, Object constraints)
void add(Component comp, Object constraints, int index)
• setLayout is used to associate a layout manager to a container. Panel class has a constructor
that takes a layout manager. getLayout returns the associated layout manager.
• It is recommended that the layout manager be associated with the container before any
component is added. If we associate the layout manager after the components are added and
the container is already made visible, the components appear as if they have been added by
the previous layout manager (if none was associated before, then the default). Only
subsequent operations (such as resizing) on the container use the new layout manager. But if
the container was not made visible before the new layout is added, the components are re-laid
out by the new layout manager.
• Positioning can be done manually by passing null to setLayout.
• Flow Layout Manager
 Honors components preferred size.(Doesn’t constraint height or width)
 Arranges components in horizontal rows, if there’s not enough space, it creates
another row.
 If the container is not big enough to show all the components, Flow Layout
Manager does not resize the component, it just displays whatever can be displayed in the
space the container has.
 Justification (LEFT, RIGHT or CENTER) can be specified in the constructor of
layout manager.
 Default for applets and panels.
• Grid Layout Manager
 Never honors the components’ preferred size
 Arranges the components in no of rows/columns specified in the constructor.
Divides the space the container has into equal size cells that form a matrix of
rows/columns.
 Each component will take up a cell in the order in which it is added (left to right,
row by row)

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
 Each component will be of the same size (as the cell)
 If a component is added when the grid is full, a new column is created and the
entire container is re-laid out.
• Border Layout Manager
 Divides the container into 5 regions – NORTH, SOUTH, EAST, WEST and
CENTER
 When adding a component, specify which region to add. If nothing is specified,
CENTER is assumed by default.
 Regions can be specified by the constant strings defined in BorderLayout (all
upper case) or using Strings (Title case, like North, South etc)
 NORTH and SOUTH components – height honored, but made as wide as the
container. Used for toolbars and status bars.
 EAST and WEST components – width honored, but made as tall as the container
(after the space taken by NORTH, SOUTH components). Used for scrollbars.
 CENTER takes up the left over space. If there are no other components, it gets all
the space.
 If no component is added to CENTER, container’s background color is painted in
that space.
 Each region can display only one component. If another component is added, it
hides the earlier component.

• Card Layout Manager


 Draws in time rather than space. Only one component displayed at a time.
 Like a tabbed panel without tabs. (Can be used for wizards interface, i.e. by
clicking next, displays the next component)
 Components added are given a name and methods on the CardLayout manager
can be invoked to show the component using this name. Also the manager contains
methods to iterate through the components. For all methods, the parent container should
be specified.
first(Container parent)
next(Container parent)
previous(Container parent)
last(Container parent)
show(Container parent, String name)
 Component shown occupies the entire container. If it is smaller it is resized to fit
the entire size of the container. No visual clue is given about the container has other
components.
• Gridbag Layout Manager
 Like the GridLayout manger uses a rectangular grid.
 Flexible. Components can occupy multiple cells. Also the width and height of the
cells need not be uniform. i.e A component may span multiple rows and columns but the
region it occupies is always rectangular. Components can have different sizes (which is
not the case with Grid layout)

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
 Requires lot of constraints to be set for each component that is added.
 GridBagConstraints class is used to specify the constraints.
 Same GridBagConstraints object can be re-used by all the components.

Event Handling

Event Classes
• Events are Java objects. All the pertinent information is encapsulated in that object. The
super class of all events is java.util.EventObject.
• This java.util.EventObject class defines a method that returns the object that generated the
event:
Object getSource()
• All events related to AWT are in java.awt.event package. AWTEvent is the abstract super
class of all AWT events. This class defines a method that returns the ID of the event. All
events define constants to represent the type of event.
int getID() – returns an int in the form of an integer value that identifies the type of event.
• It is useful to divide the event classes into Semantic events and Low-level events.
• Semantic Events –
These classes are used for high-level semantic events, to represent user interaction with GUI.
ActionEvent, AdjustmentEvent, ItemEvent, TextEvent

Event Class Source Event Types


Button – when clicked ACTION_PERFORMED
List – when doubleclicked
ActionEvent
MenuItem – when clicked
TextField – when Enter key is pressed
AdjustmentEv Scrollbar – when adjustments are made ADJUSTMENT_VALUE_CHANG
ent ED
CheckBox – when selected or ITEM_STATE_CHANGED
deselected
CheckboxMenuItem – same as
checkbox
ItemEvent
Choice – when an item is selected or
deselected
List - when an item is selected or
deselected

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
TextField TEXT_VALUE_CHANGED
TextEvent
TextArea

Methods defined in the events to get the information about them.


Event Class Method Description
String Returns the command name associated with this action
getActionCommand
int getModifiers Returns the sum of modifier constants corresponding to
ActionEvent
the keyboard modifiers held down during this action.
SHIFT_MASK, ALT_MASK, CTRL_MASK,
META_MASK
AdjustmentEv int getvalue Returns the current value designated by the adjustable
ent component
Object getItem Returns the object that was selected or deselected
Label of the checkbox
ItemEvent int getStateChange Returned value indicates whether it was a selection or a
SELECTED de-selection that took place, given by the two constants
DESELECTED in ItemEvent.
• Low-level Events –
These classes are used to represent low-level input or window operations. Several low-level
events can constitute a single semantic event.
ComponentEvent, ContainerEvent, FocusEvent, KeyEvent, MouseEvent, PaintEvent,
WindowEvent

Event Class Source Event Types


COMPONENT_SHOWN, COMPONENT_HIDDEN,
ComponentEv All COMPONENT_MOVED, COMPONENT_RESIZED
ent components AWT handles this event automatically. Programs should not
handle this event.
COMPONENT_ADDED, COMPONENT_REMOVED
ContainerEve
All containers AWT handles this event automatically. Programs should not
nt
handle this event.
FOCUS_GAINED, FOCUS_LOST
All
FocusEvent Receiving focus means the component will receive all the
components
keystrokes.
All This is an abstract class. Parent of KeyEvent and MouseEvent.
InputEvent
components Constants for key and mouse masks are defined in this class.
All KEYPRESSED, KEYRELEASED, KEYTYPED (when a
KeyEvent
components character is typed)
MOUSE_PRESSED, MOUSE_RELEASED,
All
MouseEvent MOUSE_CLICKED, MOUSE_DRAGGED, MOUSE_MOVED,
components
MOUSE_ENTERED, MOUSE_EXITED

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
This event occurs when a component should have its
paint()/update() methods invoked. AWT handles this event
All
PaintEvent automatically. Programs should not handle this event. This event is
components
not supposed to be handled by the event listener model.
Components should override paint/update methods to get rendered.
This event is generated when an important operation is performed
on a window.
WINDOW_OPENED, WINDOW_CLOSING,
WindowEvent All windows
WINDOW_CLOSED, WINDOW_ICONIFIED,
WINDOW_DEICONIFIED, WINDOW_ACTIVATED,
WINDOW_DEACTIVATED

Methods defined in the events to get the information about them.


Event Class Method Description
ComponentEv Component Returns a reference to the same object as getSource, but
ent getComponent the returned reference is of type Component.
Container Returns the container where this event originated.
getContainer
ContainerEve
nt Component getChild Returns the child component that was added or removed
in this event

FocusEvent boolean isTemporary Determines whether the loss of focus is permanent or


temporary
long getWhen Returns the time the event has taken place.
int getModifiers Returns the modifiers flag for this event.
InputEvent
void consume Consumes this event so that it will not be processed in
the default manner by the source that originated it.

int getKeyCode For KEY_PRESSED or KEY_RELEASED events, this


method can be used to get the integer key-code
associated with the key. Key-codes are defined as
KeyEvent
constants is KeyEvent class.
char getKeyChar For KEY_TYPED events, this method returns the
Unicode character that was generated by the keystroke.
int getX
Return the position of the mouse within the originated
int getY
MouseEvent component at the time the event took place
Point getPoint
int getClickCount Returns the number of mouse clicks.
WindowEvent Window getWindow Returns a reference to the Window object that caused the
event to be generated.
Event Listeners
• Each listener interface extends java.util.EventListener interface.

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
• There are 11 listener interfaces corresponding to particular events. Any class that wants to
handle an event should implement the corresponding interface. Listener interface methods
are passed the event object that has all the information about the event occurred.
• Then the listener classes should be registered with the component that is the source/originator
of the event by calling the addXXXListener method on the component. Listeners are
unregistered by calling removeXXXListener method on the component.
• A component may have multiple listeners for any event type.
• A component can be its own listener if it implements the necessary interface. Or it can handle
its events by implementing the processEvent method. (This is discussed in explicit event
enabling section)
• All registered listeners with the component are notified (by invoking the methods passing the
event object). But the order of notification is not guaranteed (even if the same component is
registered as its own listener). Also the notification is not guaranteed to occur on the same
thread. Listeners should take cautions not to corrupt the shared data. Access to any data
shared between the listeners should be synchronized.
• Same listener object can implement multiple listener interfaces.
• Event listeners are usually implemented as anonymous classes.

Event Type Event Source Listener Registration and Event Listener Interface
removal methods provided implemented by a listener
by the source
ActionEvent Button addActionListener ActionListener
List removeActionListner
MenuItem
TextField
AdjustmentEv Scrollbar addAdjustmentListener AdjustmentListener
ent removeAdjustmentListner
ItemEvent Choice addItemListener ItemListener
List removeItemListner
Checkbox
CheckboxMenuI
tem
TextEvent TextField addTextListener TextListener
TextArea removeTextListner
ComponentEv Component add ComponentListener ComponentListener
ent remove ComponentListner
ContainerEven Container addContainerListener ContainerListener
t removeContainerListner
FocusEvent Component addFocusListener FocusListener
removeFocusListner
KeyEvent Component addKeyListener KeyListener
removeKeyListner

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
addMouseListener MouseListener
removeMouseListner
MouseEvent Component
addMouseMotionListener MouseMotionListener
removeMouseMotionListner
WindowEvent Window addWindowListener WindowListener
removeWindowListner

Event Listener interfaces and their methods:

Event Listener Event Listener Methods


Interface
ActionListener void actionPerformed(ActionEvent evt)
AdjustmentListener void adjustmentValueChanged(AdjustmentEvent evt)
ItemListener void itemStateChanged(ItemEvent evt)
TextListener void textValueChanged(TextEvent evt)
ComponentListener void componentHidden(ComponentEvent evt)
void componentShown(ComponentEvent evt)
void componentMoved(ComponentEvent evt)
void componentResized(ComponentEvent evt)
ContainerListener void componentAdded(ContainerEvent evt)
void componentRemoved(ContainerEvent evt)
FocusListener void focusGained(FocusEvent evt)
void focusLost(FocusEvent evt)
KeyListener void keyPressed(KeyEvent evt)
void keyReleased(KeyEvent evt)
void keyTyped(KeyEvent evt)
MouseListener void mouseClicked(MouseEvent evt)
void mouseReleased(MouseEvent evt)
void mousePressed(MouseEvent evt)
void mouseEntered(MouseEvent evt)
void mouseExited(MouseEvent evt)
MouseMotionListene void mouseDragged(MouseEvent evt)
r void mouseMoved(MouseEvent evt)
WindowListener void windowActivated(WindowEvent evt)
void windowDeactivated(WindowEvent evt)
void windowIconified(WindowEvent evt)
void windowDeiconified(WindowEvent evt)
void windowClosing(WindowEvent evt)
void windowClosed(WindowEvent evt)
BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
void windowOpened(WindowEvent evt)

Event Adapters
• Event Adapters are convenient classes implementing the event listener interfaces. They
provide empty bodies for the listener interface methods, so we can implement only the
methods of interest without providing empty implementation. They are useful when
implementing low-level event listeners.
• There are 7 event adapter classes, one each for one low-level event listener interface.
• Obviously, in semantic event listener interfaces, there is only one method, so there is no need
for event adapters.
• Event adapters are usually implemented as anonymous classes.

Explicit Event Enabling


How events are produced and handled?
• OS dispatches events to JVM. How much low-level processing is done by OS or JVM
depends on the type of the component. In case of Swing components JVM handles the low-
level events.
• JVM creates event objects and passes them to the components.
• If the event is enabled for that component, processEvent method in that component (inherited
from java.awt.Component) is called. Default behavior of this method is to delegate the
processing to more specific processXXXEvent method. Then this processXXXEvent method
invokes appropriate methods in all registered listeners of this event.
• All the registered listeners of the event for the component are notified. But the order is not
guaranteed.
• This delegation model works well for pre-defined components. If the component is
customized by sub-classing another component, then it has the opportunity to handle its own
events by implementing appropriate processXXXEvent methods or the processEvent method
itself.
• To handle its own events, the subclass component must explicitly enable all events of
interest. This is done by calling enableEvents method with appropriate event masks in the
constructor. Enabling more than one event requires OR’ing corresponding event masks.
These event masks are defined as constants in java.awt.AWTEvent.
• If the component wants to also notify the registered listeners for the event, then the
overriding methods should call the parent version of the methods explicitly.
• Component class has a method processMouseMotionEvent, even though there is no event
called MouseMotionEvent.

Steps for handling events using listeners or by the same component

Delegating to listeners Handling own events (explicit enabling)

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
1. Create a listener class, either by 1. Create a subclass of a component
implementing an event listener interface 2. Call
or extending an event adapter class. enableEvents(XXX_EVENT_MASK) in
2. Create an instance of the component the constructor.
3. Create an instance of the listener class 3. Provide processXXXEvent and/or
4. Call addXXXListener on the component processEvent in the subclass component.
passing the listener object. (This step If also want to notify the listeners, call
automatically enables the processing of parent method.
this type of event. Default behavior of 4. Create an instance of the subclass
processEvent method in the component component
is to delegate the processing to
processXXXEvent and that method will
invoke appropriate listener class
methods.)

AWT Components
The Java programming language class library provides a user interface toolkit called the
Abstract Windowing Toolkit, or the AWT. The AWT is both powerful and flexible.

• Java’s building blocks for creating GUIs.


• All non-menu related components inherit from java.awt.Component, that provides basic
support for event handling, controlling component size, color, font and drawing of
components and their contents.
• Component class implements ImageObserver, MenuContainer and Serializable interfaces. So
all AWT components can be serialized and can host pop-up menus.
• Component methods:

Controls Methods / Description


Size Dimension getSize()
void setSize(int width, int height)
void setSize(Dimension d)
Location Point getLocation()
void setLocation(int x, int y)
void setLocation(Point p)
Size and Rectangle getBounds()
Location void setBounds (int x, int y, int width, int height)
void setBounds (Rectangle r)

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
Color void setForeground(Color c)
void setBackground(Color c)
Font void setFont(Font f)
void setFont(Font f)
Visibility void setEnabled(boolean b)
and void setVisible(boolean b)
Enabling

• Container class extends Component. This class defines methods for nesting components in a
container.
Component add(Component comp)
Component add(Component comp, int index)
void add(Component comp, Object constraints)
void add(Component comp, Object constraints, int index)

void remove(int index)


void remove(Component comp)
void removeAll()
• The following are the containers:

Contain Description
er
Panel • Provides intermediate level of spatial organization and containment.
• Not a top-level window
• Does not have title, border or menubar.
• Can be recursively nested.
• Default layout is Flow layout.
Applet • Specialized Panel, run inside other applications (typically browsers)
• Changing the size of an applet is allowed or forbidden depending on the
browser.
• Default layout is Flow layout.
Window • Top-level window without a title, border or menus.
• Seldom used directly. Subclasses (Frame and Dialog) are used.
• Defines these methods:
• void pack() – Initiates layout management, window size might be
changed as a result
• void show() – Makes the window visible, also brings it to front
• void dispose() – When a window is no longer needed, call this to
free resources.

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
Frame • Top-level window (optionally user-resizable and movable) with a title-bar, an
icon and menus.
• Typically the starting point of a GUI application.
• Default layout is Border layout.
Dialog • Top-level window (optionally user-resizable and movable) with a title-bar.
• Doesn’t have icons or menus.
• Can be made modal.
• A parent frame needs to be specified to create a Dialog.
• Default layout is Border layout.
ScrollPa • Can contain a single component. If the component is larger than the scrollpane,
ne it acquires vertical / horizontal scrollbars as specified in the constructor.
• SCROLLBARS_AS_NEEDED – default, if nothing specified
• SCROLLBARS_ALWAYS
• SCROLLBARS_NEVER

• Top-level containers (Window, Frame and Dialog) cannot be nested. They can contain other
containers and other components.
• GUI components:

Compone Description Constructors Events


nt
Button • A button with a textual label. new Button(“Apply”) Action event.

Canvas • No default appearance. Mouse,


• Can be sub-classed to create custom MouseMotio
drawing areas. n, Key
events.

Checkbox • Toggling check box. Checkbox(String label) Item event


• Default initial state is false.
• getState(), setState(boolean state) -
methods
Checkbox(String label,
• Can be grouped with a
boolean initialstate)
CheckboxGroup to provide radio
behavior.
• Checkboxgroup is not a subclass of
Component. Checkbox(String label,
• Checkboxgroup provides these CheckBoxGroup
methods: getSelectedCheckbox and group)
setSelectedCheckbox(Checkbox
new)
Choice • A pull-down list Item event
• Can be populated by repeatedly
BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
calling addItem(String item)
method.
• Only the current choice is visible.
FileDialog • Subclass of Dialog FileDialog(Frame
• Open or Save file dialog, modal parent, String title, int
• Dialog automatically removed, after mode)
user selects the file or hits cancel.
• getFile(), getDirectory() methods
can be used to get information about
the selected file. Mode can be
FileDialog.LOAD or

FileDialog.SAVE

Label • Displays a single line of read-only Label() None


non-selectable text
• Alignment can be Label(String label)
Label.LEFT, Label.RIGHT or
Label(String label, int
Label.CENTER
align)

List • Scrollable vertical list of text items. List() Item event –


• No of visible rows can be specified, selecting or
if not specified layout manager List(int nVisibleRows) deselecting
determines this.
List(int nVisibleRows,
• Acquires a vertical scrollbar if
needed. boolean
• List class methods: multiSelectOK) Action event
•addItem(String), addItem(String, – double
int index) clicking
•getItem(int index),
getItemCount()
•getRows() – no of visible rows
•int getSelectedIndex()
•int[] getSelectedIndexes()
•String getSelectedItem()
•String[] getSelectedItems()

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
Scrollbar • With the last form of constructor, Scrollbar() – a vertical Adjustment
calculate the spread as maxvalue – scrollbar. event
minvalue. Then the slider width is
slidersize / spread times of scrollbar Scrollbar(int
width. orientation)

Scrollbar(int
orientation, int
initialvalue, int
slidersize, int minvalue,
int maxvalue)

Orientation can be

Scrollbar.HORIZONT
AL

Scrollbar.VERTICAL

TextField • Extends TextComponent TextField() – empty Text event


• Single line of edit / display of text. field
• Scrolled using arrow keys.
• Depending on the font, number of TextField(int ncols) –
size Action event
displayable characters can vary.
– Enter key is
• But, never changes size once
created. TextField(String text) – pressed.
• Methods from TextComponent: initial text
• String getSelectedText()
TextField(String text,
• String getText()
int ncols) – initial text
• void setEditable(boolean
editable) and size
• void setText(String text)

TextArea • Extends TextComponent TextArea() – empty Text event


• Multiple lines of edit/display of text. area
• Scrolled using arrow keys.
• Can use the TextComponent TextArea(int nrows, int
methods specified above. ncols) – size
• Scroll parameter in last constructor
form could be TextArea(String text) –
TextArea.SCROLLBARS_BOTH, initial text

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
TextArea.SCROLLBARS_NONE, TextArea(String text,
TextArea.SCROLLBARS_HORIZ int nrows, int ncols) –
ONTAL_ONLY initial text and size
TextArea.SCROLLBARS_VERTI
CAL_ONLY TextArea(String text,
int nrows, int ncols, int
scroll)

• Pull-down menus are accessed via a menu bar, which can appear only on Frames.
• All menu related components inherit from java.awt.MenuComponent
• Steps to create and use a menu
• Create an instance of MenuBar class
• Attach it to the frame – using setMenubar() method of Frame
• Create an instance of Menu and populate it by adding MenuItems,
CheckboxMenuItems, separators and Menus. Use addSeparator() method to add
separators. Use add() method to add other items.
• Attach the Menu to the MenuBar. Use add() method of Menubar to add a menu to
it. Use setHelpMenu to set a particular menu to appear always as right-most menu.
• Menu(String label) – creates a Menu instance. Label is what displayed on the Menubar. If
this menu is used as a pull-down sub-menu, label is the menu item’s label.
• MenuItems generate Action Events.
CheckboxMenuItems generate Item Events.

Image on Frame in Java AWT


In this section, you will learn how to display image on the frame. This program shows you how
to display image in your application.

In this program, there are three methods have been used to display the image on the frame in
your application. These are explained below :

main() :
This is the main() method of the program from which your program starts to execute the program
in sequence. This method has simply create the instance for the AwtImage class.

AwtImage() :
This is the constructor of the AwtImage class in which, the instance of the MediaTracker class
BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
has been created to add the image on the frame using the addImage() method of the
MediaTracker class. This constructor set the size, visibility and the close operation on the close
button of the frame.

MediaTracker :
MediaTracker is the class of java.awt.*; package, has been used. MediaTracker is a utility
class that tracks the status of a number of media objects. And this type of object can include
images and audio clips. In this program only the explanation about the adding images has been
given. MediaTracker class is used after creating the instance for that and calling the addImage()
of the MediaTracker.

addImage() :
This is the addImage() method of the MediaTracker class which is used load the image. Then
the addImage() method of the MediaTracker has been used. Syntax of the addImage() function
is MediaTracker.addImage(img, x, y, x1, y1). Arguments of addImage() function is explained
below :

img - image name type of Image.


x - lower X - Coordinate type of int.
y - lower Y - Coordinate type of int.
x1 - upper X - Coordinate type of int.
y1 - upper Y - Coordinate type of int.

Here is code of the program :

import java.awt.*;
import java.awt.event.*;

public class AwtImage extends Frame{


Image img;
public static void main(String[] args){
AwtImage ai = new AwtImage();
}

public AwtImage(){
super("Image Frame");
MediaTracker mt = new MediaTracker(this);
img = Toolkit.getDefaultToolkit().getImage("icon_confused.gif");
mt.addImage(img,0);
setSize(400,400);
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
dispose();
}
});
}
public void update(Graphics g){
paint(g);

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
}

public void paint(Graphics g){


if(img != null)
g.drawImage(img, 100, 100, this);
else
g.clearRect(0, 0, getSize().width, getSize().height);
}
}

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)

BY:-KAPIL KUMAR GUPTA

(Astt. Professor)

You might also like