0% found this document useful (0 votes)
4 views5 pages

Java Applets Servlets

Uploaded by

pratiknaskar.11
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)
4 views5 pages

Java Applets Servlets

Uploaded by

pratiknaskar.11
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

Highly Descriptive Exam-Style Notes on Java

Applets, GUI, Event Handling, Graphics, and


Servlets

1. Java Applets
Introduction to Applets
An applet is a small Java program that runs within the context of a browser or an applet
viewer. Unlike standalone Java applications, which rely on the main() method for
execution, applets rely on a well-defined life cycle managed by the browser. Applets
were one of the earliest methods to embed interactive programs into web pages,
enabling features like animations, dynamic data visualization, games, and educational
tools. Since applets run inside the restricted environment of the browser, they follow a
sandbox security model which prevents unauthorized access to local system
resources like files, hardware, or the network. This was important for internet security
but limited the power of applets compared to desktop applications.

Applet Life Cycle


The behavior of applets is governed by their life cycle methods, defined in the Applet
class: 1. init() – This is the initialization stage, executed only once during the lifetime of
the applet. It is used to allocate resources, initialize variables, or set up user interface
components. 2. start() – This is called every time the applet becomes active, for
example when the page is revisited or the applet window is restored. It is often used to
start animations or background threads. 3. paint(Graphics g) – This method is called
whenever the applet needs to redraw its content. It is passed a Graphics object that
provides drawing capabilities. This is the most important method for rendering shapes,
images, and text. 4. stop() – This method is called when the user navigates away from
the page. It is typically used to suspend animations, pause threads, or release
temporary resources. 5. destroy() – This method is executed once, just before the
applet is unloaded from memory. It is responsible for final cleanup tasks, such as
closing files or releasing permanent resources.
Together, these methods provide a structured framework for managing the applet’s
behavior throughout its lifecycle.

Writing and Running Applets


To write an applet, programmers extend the Applet class and override the life cycle
methods according to requirements. The applet can be embedded into an HTML page
using the <applet> tag, specifying attributes like code, width, and height. For example:
<applet code="MyApplet.class" width=400 height=400></applet>
Modern browsers have deprecated applet support, but applets can still be executed with
the appletviewer tool for academic or legacy purposes.

2. Working with Graphics in Applets


The Graphics class in the java.awt package is central to drawing operations in applets.
It provides a wide variety of methods to draw primitive shapes, images, and text. Every
time the system decides that a portion of the screen needs to be redrawn, it invokes the
paint(Graphics g) method, passing a Graphics object.

Some common methods include: - drawLine(x1, y1, x2, y2) – draws a line between
two points. - drawRect(x, y, width, height) and fillRect() – draw or fill rectangles. -
drawOval() and fillOval() – for circles and ellipses. - drawPolygon() and
fillPolygon() – for polygons with multiple vertices. - drawString("Hello", x, y) –
displays a string at specific coordinates.
In addition, developers can use setColor(Color c) to change the drawing color, and
setFont(Font f) to select the font style and size. Java uses a pixel-based coordinate
system with the origin (0,0) at the top-left corner of the applet window. This makes it
easy to control placement of graphical elements precisely.

3. Incorporating Images and Sounds


Java applets can enhance interactivity by incorporating multimedia elements: - Images
can be loaded using the getImage() method, which takes the document base URL and
filename as parameters. Once loaded, images are displayed using drawImage() from
the Graphics class. - Sounds can be included using the AudioClip interface. This
provides methods such as play(), loop(), and stop(). For instance, background music
can be looped continuously while an applet runs, while sound effects can be triggered
by user actions like mouse clicks.
By combining graphics, images, and sounds, applets can create rich and engaging
experiences.

4. Event Handling in Java


Java GUI applications are event-driven, meaning the program waits for user actions
(events) and responds accordingly. The Event Delegation Model is the framework that
governs this process. It involves: 1. Event Source – the component that generates the
event (e.g., button click). 2. Event Object – an object that encapsulates event
information (e.g., which key was pressed, which mouse button was clicked). 3. Event
Listener – an interface with methods that must be implemented to handle specific
events.
When a user performs an action, such as pressing a button, the event source creates
an event object and sends it to all registered event listeners. These listeners then
execute the appropriate response code. This delegation model is efficient, as the source
does not directly handle the event, but delegates it to listeners.

Common Event Classes


 ActionEvent – generated by button clicks or menu selections.
 MouseEvent – generated by mouse actions like clicking, entering, exiting, or
dragging.
 KeyEvent – generated by keyboard actions.
 WindowEvent – generated by window actions such as opening, closing,
minimizing, or maximizing.
Listener Interfaces and Adapter Classes
Each event class has a corresponding listener interface: - ActionListener →
actionPerformed() - MouseListener → mouseClicked(), mousePressed(), etc. -
KeyListener → keyPressed(), keyReleased(), keyTyped() - WindowListener →
windowOpened(), windowClosing(), etc.

Sometimes listener interfaces contain multiple abstract methods, but the programmer
may need only one. To simplify coding, Java provides Adapter Classes (like
MouseAdapter, WindowAdapter) that offer empty implementations of all methods. The
programmer can then override only the method of interest.

Inner Classes for Event Handling


In many small applications, developers prefer anonymous inner classes to implement
event handling. These provide a compact way to associate event-handling code directly
with the component that generates the event.

5. GUI Design using AWT Controls


The Abstract Window Toolkit (AWT) was Java’s first GUI library. It provides basic
graphical components that rely on the host operating system’s resources (hence called
“heavyweight components”). Some common AWT components are: - Label – used for
displaying read-only text. - Button – for clickable actions. - TextField – allows single-
line text input. - TextArea – allows multi-line text input. - Checkbox and
CheckboxGroup – for multiple or mutually exclusive selections. - Choice and List – for
dropdown menus and scrollable lists. - Canvas – for custom graphics rendering.

Containers and Layout Managers


AWT uses containers (Frame, Panel, Dialog, Applet) to hold components. Containers
rely on layout managers to control how components are arranged: - FlowLayout –
arranges components in rows, automatically wrapping. - BorderLayout – divides the
space into five regions (North, South, East, West, Center). - GridLayout – arranges
components in equal-sized grid cells. - CardLayout – allows multiple components to
occupy the same space, switching like a deck of cards.
This system ensures GUIs are adaptable across different screen sizes and resolutions.

6. Swing Components (JFC)


Swing is an advanced GUI toolkit that extends AWT, providing lightweight, platform-
independent components. Unlike AWT, Swing components do not depend on native
operating system peers, making them more flexible.

Common Swing Components


 JFrame – top-level container window.
 JPanel – lightweight container for grouping components.
 JLabel – for displaying text or images.
 JButton – for clickable actions.
 JTextField and JTextArea – for text input.
 JRadioButton and JCheckBox – selection options.
 JComboBox – dropdown selection.
 JMenuBar, JMenu, JMenuItem – for building menus.
 JTabbedPane, JSplitPane, JScrollPane – advanced UI elements.
Swing Events
Swing event handling follows the same delegation model as AWT. However, Swing
adds features such as pluggable look-and-feel, tooltips, and more refined component
behavior, making it the preferred choice for modern Java GUIs.

7. Graphics in Java (Detailed)


Java supports two levels of graphics: basic drawing with Graphics and advanced
drawing with Graphics2D. Developers can draw primitive shapes, fill them with colors,
apply gradients, and even perform geometric transformations like scaling, rotation, and
translation. The Graphics2D class introduces rendering hints, enabling smooth edges
and high-quality visuals.
Fonts are controlled with the Font class, allowing customization of family, style, and
size. Combined with drawString(), it allows developers to create custom headers,
labels, or even stylized text-based graphics.
8. Servlets (Overview)
Introduction to Servlets
A Servlet is a server-side Java program that handles requests from clients (usually
browsers) and generates dynamic web content. Servlets replaced earlier CGI scripts
because they are more efficient: instead of creating a new process for each request,
servlets use threads to handle multiple requests within a single JVM. This reduces
memory and CPU usage, making servlets scalable and suitable for enterprise
applications.

Servlet Life Cycle


Servlets are managed by a Servlet Container (like Apache Tomcat), which controls
their life cycle: 1. init() – executed once when the servlet is first loaded, used for
initialization tasks. 2. service() – executed for each client request, processing input and
sending output. 3. destroy() – executed once when the servlet is unloaded, used for
releasing resources.

Types of Servlets
 GenericServlet – protocol-independent base class.
 HttpServlet – extends GenericServlet, designed specifically for HTTP protocol. It
defines methods such as doGet() and doPost() for handling HTTP requests.
Servlet Architecture
The servlet architecture can be summarized as: 1. Client sends a request via browser.
2. The request reaches the Servlet Container. 3. Servlet processes the request using
HttpServletRequest and sends a response using HttpServletResponse. 4. The
response is returned to the client.

Applications of Servlets
Servlets are used for form processing, online shopping carts, authentication systems,
dynamic page generation, and session management. They also serve as the foundation
for advanced Java frameworks like JSP, Spring MVC, and Struts.

✅Final Summary
This expanded set of notes provides detailed, paragraph-based explanations suitable
for university exams. Each section has been elaborated with context, practical
applications, and theoretical background. With this level of detail, you can confidently
write longer answers in exams while still maintaining compactness and clarity.

You might also like