0% found this document useful (0 votes)
6 views

unit-3_Java

Java Applets are Java programs that run in web browsers, embedded in HTML files, and executed in a secure sandbox environment. They follow a specific life cycle with methods like init(), start(), paint(), stop(), and destroy() for managing their execution. Java AWT provides the necessary classes and components for creating graphical user interfaces in Java applications.

Uploaded by

shrikant4udude
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

unit-3_Java

Java Applets are Java programs that run in web browsers, embedded in HTML files, and executed in a secure sandbox environment. They follow a specific life cycle with methods like init(), start(), paint(), stop(), and destroy() for managing their execution. Java AWT provides the necessary classes and components for creating graphical user interfaces in Java applications.

Uploaded by

shrikant4udude
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Java Applets

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( ).

Key Packages for Java Applets


 java.applet.Applet: Base class for applets.
 java.awt.Graphics: Used for drawing on the applet screen.
 java.awt: Provides GUI components and event-handling mechanisms.
Creating Hello World Applet
Let’s begin with the HelloWorld applet :
import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorld extends Applet {

// Overriding paint() method


public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}
}

Running the HelloWorld Applet


After you enter the source code for HelloWorld.java, compile in the same way that you
have been compiling java programs (using javac command). However, running HelloWorld
with the java command will generate an error because it is not an application.
java HelloWorld
Error: Main method not found in class HelloWorld, please define the main method as:
public static void main(String[] args)
There are two standard ways in which you can run an applet:
1. Executing the applet within a Java-compatible web browser.
2. Using an applet viewer, such as the standard tool, applet-viewer. An applet viewer
executes your applet in a window. This is generally the fastest and easiest way to test
your applet.
Each of these methods is described next.
1. Using java enabled web browser
 To execute an applet in a web browser we have to write a short HTML text file that
contains a tag that loads the applet.
 We can use APPLET or OBJECT tag for this purpose
 Using APPLET, here is the HTML file that executes HelloWorld
<applet code=”HelloWorld” width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the
applet. The APPLET tag contains several other options. After you create this html file, you
can use it to execute the applet.
Note: Chrome and Firefox no longer supports NPAPI (technology required for Java
applets).
2. Using appletviewer
 This is the easiest way to run an applet.
 To execute HelloWorld with an applet viewer, you may also execute the HTML file
shown earlier.
 For example, if the preceding HTML file is saved with RunHelloWorld.html, then the
following command line will run HelloWorld.
appletviewer RunHelloWorld.html
3. appletviewer with Java Source File
If you include a comment at the head of your Java source code file that contains the
APPLET tag then your code is documented with a prototype of the necessary HTML
statements, and you can run your compiled applet merely by starting the applet viewer with
your Java source code file. If you use this method, the HelloWorld source file looks like
this:
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;

/*
<applet code="HelloWorld" width=200 height=60>
</applet>
*/

// HelloWorld class extends Applet


public class HelloWorld extends Applet
{
// Overriding paint() method
@Override
public void paint(Graphics g)
{
g.drawString("Hello World", 20, 20);
}

}
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.*;

//to access showStatus()


import java.awt.*;//Graphic

//class is available in this package


import java.util.Date;

//to access Date object


public class GFG extends Applet
{
public void paint(Graphics g)
{

Date dt = new Date();


super.showStatus("Today is" + dt);

//in this line, super keyword is


// avoidable too.
}
}
Note: Here, we can see that if the screen is maximized or minimized we will get an updated
time. This shows that paint() is called again and again.
Features of Applets over HTML
 Displaying dynamic web pages of a web application.
 Playing sound files.
 Displaying documents
 Playing animations
Restrictions imposed on Java applets
Due to security reasons, the following restrictions are imposed on Java applets:
 An applet cannot load libraries or define native methods.
 An applet cannot ordinarily read or write files on the execution host.
 An applet cannot read certain system properties.
 An applet cannot make network connections except to the host that it came from.
 An applet cannot start any program on the host that’s executing it.
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.

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.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Components

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

There are four types of containers in Java AWT:

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 add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the
component.

public void setLayout(LayoutManager m) Defines the layout manager for the


component.

public void setVisible(boolean status) Changes the visibility of the component, by


default false.

Java AWT Example

To create simple AWT example, you need a frame. There are two ways to create a GUI using
Frame in AWT.

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

AWT Example by Inheritance

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

// importing Java AWT class


import java.awt.*;

// extending Frame class to our class AWTExample1


public class AWTExample1 extends Frame {

// initializing using constructor


AWTExample1() {

// creating a button
Button b = new Button("Click Me!!");

// setting button position on screen


b.setBounds(30,100,80,30);

// adding button into frame


add(b);

// frame size 300 width and 300 height


setSize(300,300);

// setting the title of Frame


setTitle("This is our basic AWT example");

// no layout manager
setLayout(null);

// now frame will be visible, by default it is not visible


setVisible(true);
}

// main method
public static void main(String args[]) {

// creating instance of Frame class


AWTExample1 f = new AWTExample1();

}
Output:

AWT Example by Association

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() {

Frame f = new Frame();

Label l = new Label("Employee id:");

Button b = new Button("Submit");

TextField t = new TextField();

// setting position of above components in the frame


l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);

// adding components into frame


f.add(b);
f.add(l);
f.add(t);

f.setSize(400,300);
f.setTitle("Employee info");

f.setLayout(null);

f.setVisible(true);
}

public static void main(String args[]) {

// creating instance of Frame class


AWTExample2 awt_obj = new AWTExample2();

}
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

1 Button It is a simple push button that triggers an


action when clicked.

2 Canvas It is a blank rectangular area where custom


graphics can be drawn.

3 Checkbox It is a component that allows the user to


select or deselect an option.

4 Choice It is a drop-down list that allows the user


to select a single item from a predefined
set of options.

5 Label It is a component that displays static text.

6 List It is a component that displays a scrollable


list of items, allowing the user to select
one or more items.

7 Scrollbar It is a component that allows the user to


scroll through a large amount of content
that exceeds the visible area.

8 TextArea It is a multi-line text input area where the


user can enter and edit text.

9 TextField It is a single-line text input area where the


user can enter and edit text.

10 Frame It is a top-level window with a title bar


and border, used as the main container for
other AWT components.

11 Panel It is a container that can hold other


components, but does not have a title bar
or border.

12 Dialog It is a pop-up window used to display


information or get input from the user.

13 Menu It is a list of commands that can be


accessed from a menu bar.

14 MenuBar It is a bar at the top of a frame that


contains menus.

15 MenuItem It is an individual command within a


menu.

AWT Java Program

//Java Program to create AWT application in Java


import java.awt.*;
public class AwtApp extends Frame {
AwtApp(){
//Creating AWT Components
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);
Label lastName = new Label("Last Name");
lastName.setBounds(20, 80, 80, 20);
Label dob = new Label("Date of Birth");
dob.setBounds(20, 110, 80, 20);
TextField firstNameTF = new TextField();
firstNameTF.setBounds(120, 50, 100, 20);
TextField lastNameTF = new TextField();
lastNameTF.setBounds(120, 80, 100, 20);
TextField dobTF = new TextField();
dobTF.setBounds(120, 110, 100, 20);
Button sbmt = new Button("Submit");
sbmt.setBounds(20, 160, 100, 30);
Button reset = new Button("Reset");
reset.setBounds(120,160,100,30);
//Adding components on Frame
add(firstName);
add(lastName);
add(dob);
add(firstNameTF);
add(lastNameTF);
add(dobTF);
add(sbmt);
add(reset);
//Set size, layout and visibility of the frame
setSize(300,300);
setLayout(null);
setVisible(true);
}
//Creating main method to create the object of the class
public static void main(String[] args) {
AwtApp awt = new AwtApp();
}
}
Output:

Java AWT Classes

Java AWT Label

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.

Java AWT Button

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.

Java AWT Checkbox

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.

Java AWT CheckboxGroup

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.

Java AWT Choice


A Choice is a drop-down list that allows users to select one item from a list of predefined
options. It is useful for compactly presenting multiple choices in a GUI. Choice components
are easy to integrate and manage, providing a simple way to select from a list.

Java AWT List

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.

Java AWT Canvas

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.

Java AWT MenuItem & Menu

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.

Java AWT PopupMenu


A PopupMenu is a context menu that appears upon user interaction, typically via a right-
click. It provides a list of actions relevant to the interaction's context. PopupMenu is useful
for offering context-specific options without cluttering the main interface.

Java AWT Panel

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.

Java AWT Toolkit

The Toolkit class is an abstract superclass that provides a platform-independent interface to


interact with various resources and capabilities of the AWT. It includes methods to get screen
resolution, image handling, and other system-level services that support GUI operations.

Java ActionListener Interface


The ActionListener interface in Java is part of the Swing framework and is used to handle
events generated by GUI components like buttons, menus, and text fields. It provides a way
to respond to user interactions with these components by defining the actionPerformed()
method that gets invoked when an action event occurs. It is notified against ActionEvent. The
ActionListener interface belongs to java.awt.event package. It has actionPerformed() method
only.

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

The actionPerformed() method is invoked automatically whenever we click on the registered


component.

public abstract void actionPerformed(ActionEvent e);

How to write ActionListener?

The common approach is to implement the ActionListener. If we implement the


ActionListener class, we need to follow 4 steps:

1. Import Necessary Packages:

i. import java.awt.event.ActionListener;
ii. Implement ActionListener Interface:

To handle action events, we need to implement the ActionListener interface. It involves


implementing the actionPerformed() method that contains the code to be executed when an
action event occurs.
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Action event handling logic goes here
}
}
3. Register ActionListener with GUI Components:

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

Java ActionListener Example: On Button click

//step1 importing packages


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

public class ActionListenerExample implements ActionListener {


// Declare TextField as instance variable
TextField tf;

public static void main(String[] args) {


// Create an instance of the class to access tf
ActionListenerExample obj = new ActionListenerExample();

// Create a Frame (window)


Frame f = new Frame("ActionListener Example");

// Create and set up the TextField


obj.tf = new TextField();
obj.tf.setBounds(50, 50, 150, 20);

// Create a Button
Button b = new Button("Click Here");
b.setBounds(50, 100, 60, 30);

// Register ActionListener
b.addActionListener(obj);

// Add components to the Frame


f.add(b);
f.add(obj.tf);

// Set Frame properties


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// Implement actionPerformed method


public void actionPerformed(ActionEvent e) {
tf.setText("Welcome to Javatpoint.");
}
}
Output:
DBC in Java | Java Database Connectivity
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database, and processing the results. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database. There are four types of
JDBC drivers:

o JDBC-ODBC Bridge Driver


o Native Driver
o Network Protocol Driver
o Thin Driver
We have discussed the above four drivers in the next chapter.

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.

Why Should We Use JDBC?

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:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

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

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.

Steps to Establish a JDBC Connection

1. Import Required Packages

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

2. Load and Register the Driver (Optional in modern Java)

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

Connection con = DriverManager.getConnection(


"jdbc:mysql://localhost:3306/mydatabase", "username", "password");

URL format:
jdbc:mysql://<host>:<port>/<database>

4. Example: Full JDBC Connection Code

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCConnectionExample {


public static void main(String[] args) {
try {
// Load MySQL JDBC driver (optional in newer Java versions)
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydatabase", "root", "yourpassword");

System.out.println("Connection successful!");

// Close the connection


con.close();
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Database connection failed.");
e.printStackTrace();
}
}
}

Before Running:

1. Include MySQL JDBC driver JAR in your project


Download from: https://dev.mysql.com/downloads/connector/j/

Or if you're using Maven:

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

You might also like