unit-3_Java
unit-3_Java
A Java Applet is a Java program that runs inside a web browser. An Applet is embedded in
an HTML file using <applet> or <objects> tags. Applets are used to make the website more
dynamic and entertaining. Applets are executed in a sandbox for security, restricting access
to local system resources.
Key Points:
Applet Basics: Every applet is a child/subclass of the java.applet.Applet class.
Not Standalone: Applets don’t run on their own like regular Java programs. They need
a web browser or a special tool called the applet viewer (which comes with Java).
No main() Method: Applets don’t start with main() method.
Display Output: Applets don’t use System.out.prinln() for displaying the output,
instead they use graphics methods like drawString() from the AWT (Abstract Window
ToolKit).
Java Applet Life Cycle
The below diagram demonstrates the life cycle of Java Applet:
It is important to understand the order in which the various methods shown in the above
image are called.
When an applet begins, the following methods are called, in this sequence:
o init( )
o start( )
o paint( )
When an applet is terminated, the following sequence of method calls takes place:
o stop( )
o destroy( )
Let’s look more closely at these methods.
1. init( ): The init( ) method is the first method to be called. This is where you should
initialize variables. This method is called only once during the run time of your applet.
2. start( ): The start( ) method is called after init( ). It is also called to restart an applet after
it has been stopped.
3. paint( ): The paint( ) method is called each time an AWT-based applet’s output must be
redrawn. This situation can occur for several reasons. For example, the window in which
the applet is running may be overwritten by another window and then uncovered. Or the
applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever
the applet must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain
the graphics context, which describes the graphics environment in which the applet is
running. This context is used whenever output to the applet is required.
paint() is the only method among all the methods mention above (which is
parameterized).
This method is crucial for updating or redrawing the visual content of the applet.
Example:
public void paint(Graphics g)
{
// Drawing a string on the applet window
// g is an object reference of class Graphic.
g.drawString(“Hello, Applet!”, 50, 50);
}
4. stop( ): The stop( ) method is called when a web browser leaves the HTML document
containing the applet, when it goes to another page.
5. destroy( ): The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory. At this point, you should free up any
resources the applet may be using. The stop( ) method is always called before destroy( ).
/*
<applet code="HelloWorld" width=200 height=60>
</applet>
*/
}
With this approach, first compile HelloWorld.java file and then simply run the below
command to run applet :
appletviewer HelloWorld
To prove above mentioned point,i.e paint is called again and again.
To prove this, let’s first study what is “Status Bar” in Applet?
Status Bar”is available in the left bottom window of an applet. To use the status bar and
write something in it, we use method showStatus() whose prototype is public void
showStatus(String)
By default status bar shows “Applet Started”
By default background color is white.
To prove paint() method is called again and again, here is the code:
Note: This code is with respect to Netbeans IDE.
Example:
//Code to illustrate paint
//method gets called again
//and again
import java.applet.*;
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple and easy
steps.
All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram. In order to place
every component in a particular position on a screen, we need to add them to a container.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog, and Panel.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Types of Containers
1. Window
2. Panel
3. Frame
4. Dialog
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
Useful Methods of Component Class
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the
component.
To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.
AWTExample1.java
// creating a button
Button b = new Button("Click Me!!");
// no layout manager
setLayout(null);
// main method
public static void main(String args[]) {
}
Output:
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are creating a TextField, Label and Button component on the Frame.
AWTExample2.java
import java.awt.*;
class AWTExample2 {
AWTExample2() {
f.setSize(400,300);
f.setTitle("Employee info");
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java's Abstract Window Toolkit (AWT) provides a set of classes for creating graphical user
interfaces and painting graphics.
AWT Components
S. NO Component Description
A Label is a non-interactive text display element in Java AWT. It is used to present a single
line of read-only text in a GUI. Labels are often used to identify other GUI components or
provide instructions to the user. They can be aligned using constants like Label.LEFT,
Label.CENTER, and Label.RIGHT.
A Button is a GUI component that triggers an action event when clicked. It is used to perform
a specific action, such as submitting a form or initiating a process. Buttons can display text or
an image, and they support adding event listeners to handle user interactions.
Java AWT TextField
A TextField is a single-line text input component in Java AWT. It allows users to enter and
edit text. TextField supports setting the initial text, getting the text input, and adding event
listeners for actions such as pressing the Enter key.
A Checkbox is a GUI component that can be either checked or unchecked. It is used for
options where the user can select or deselect an item independently. Checkboxes can be
grouped using CheckboxGroup to allow only one selection from the group.
A CheckboxGroup is used to group a set of checkboxes where only one checkbox can be
selected at a time. This is useful for presenting a set of mutually exclusive options, similar to
radio buttons. Only one checkbox in the group can be checked at any given time.
A List component displays a list of items, allowing the user to select one or more items from
the list. It can be configured to support single or multiple selections. List is useful for
presenting multiple selectable options in a scrollable area.
A Canvas is a blank rectangular area where custom graphics can be drawn. It is a subclass of
Component and provides a surface for drawing shapes, images, or handling custom
rendering. Developers override the paint method to define custom drawing logic.
AWT Scrollbar
A Scrollbar is a component that enables users to select a value from a range by sliding a knob
along a track. It can be oriented horizontally or vertically and is useful for navigating through
large content areas or adjusting values dynamically.
MenuItem and Menu are used to create hierarchical drop-down menus in a GUI. MenuItem
represents individual menu options, while Menu groups related items together. They are
added to a MenuBar to provide structured navigation and actions in an application.
A Panel is a container that groups other components together. It is used to organize and
manage the layout of multiple GUI elements. Panels can contain other panels, allowing for
complex nested layouts and better organization of interface components.
Before using the ActionListener interface, you need to import the necessary packages. In the
case of Swing components, we typically import javax.swing.* and java.awt.event.*.
actionPerformed() Method
i. import java.awt.event.ActionListener;
ii. Implement ActionListener Interface:
After implementing the ActionListener interface, you register an instance of your class
(which implements ActionListener) with the GUI components that generate action events. It
is typically done using the addActionListener() method provided by the respective Swing
component.
ActionListnerDemo.java
import javax.swing.JButton;
public class ActionListnerDemo {
public static void main(String[] args) {
JButton button = new JButton("Click Me");
button.addActionListener(new MyActionListener());
}
}
4. Implement actionPerformed() Method
Inside the actionPerformed method of your ActionListener implementation, you specify the
action event handling logic. This method will be called whenever the action event occurs,
such as a button click:
MyActionListener.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
}
Example
// Create a Button
Button b = new Button("Click Here");
b.setBounds(50, 100, 60, 30);
// Register ActionListener
b.addActionListener(obj);
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.
The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API.
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But ODBC API uses ODBC driver that is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform the following
activities:
Do You Know
o How to connect Java application with Oracle and Mysql database using JDBC?
o What is the difference between Statement and PreparedStatement interface?
o How to print total numbers of tables and views of a database using JDBC?
o How to store and retrieve images from Oracle database using JDBC?
o How to store and retrieve files from Oracle database using JDBC?
What is API?
JDBC also provides support for handling database metadata that allows us to retrieve
information about the database, such as its tables, columns, and indexes. We can use
the DatabaseMetaData interface to obtain this information that can be useful for dynamically
generating SQL queries or for database schema introspection.
Another important feature of JDBC is its support for batch processing that allows us to group
multiple SQL statements into a batch and execute them together. It can improve performance
by reducing the number of round trips between the application and the database.
Establishing a connection in JDBC is the first step to interact with a database in Java. Here's
how to do it step-by-step with a simple example.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Class.forName("com.mysql.cj.jdbc.Driver");
In JDBC 4.0+ (Java 6+), this step is optional if you have the driver JAR in your
classpath.
But it's still common to include it for clarity and backward compatibility.
3. Create Connection
URL format:
jdbc:mysql://<host>:<port>/<database>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
System.out.println("Connection successful!");
Before Running:
xml
CopyEdit
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
2. Make sure:
o MySQL server is running
o Database exists
o Username and password are correct