Professional Documents
Culture Documents
Oos Notes
Oos Notes
(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
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.
(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
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.
(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Methods of Servlets
A Generic servlet contains the following five methods:
init()
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 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()
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.
(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()
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.
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.
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.
(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.
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.
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.
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
(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.)
(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
[edit] Relationship to AWT
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.
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 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);
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)
(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.
(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
(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
TextField TEXT_VALUE_CHANGED
TextEvent
TextArea
(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
(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
(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
addMouseListener MouseListener
removeMouseListner
MouseEvent Component
addMouseMotionListener MouseMotionListener
removeMouseMotionListner
WindowEvent Window addWindowListener WindowListener
removeWindowListner
(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.
(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.
(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)
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.
(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:
(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
(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
(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.
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 :
import java.awt.*;
import java.awt.event.*;
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);
(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
}
(Astt. Professor)
OBJECT ORIENTED STRUCTURE
(UNIT-5)
(Astt. Professor)