0% found this document useful (0 votes)
14 views39 pages

Java Unit 4&5

This document covers the fundamentals of Java Applets and GUI programming, detailing the applet lifecycle, event handling, and graphics rendering. It explains the structure of applet classes, the importance of the AWT and Swing libraries, and how to create and manage GUI components. Additionally, it provides examples of applet code and discusses the transition from Applets to more modern GUI frameworks like JavaFX.

Uploaded by

rahul.play.304
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)
14 views39 pages

Java Unit 4&5

This document covers the fundamentals of Java Applets and GUI programming, detailing the applet lifecycle, event handling, and graphics rendering. It explains the structure of applet classes, the importance of the AWT and Swing libraries, and how to create and manage GUI components. Additionally, it provides examples of applet code and discusses the transition from Applets to more modern GUI frameworks like JavaFX.

Uploaded by

rahul.play.304
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

UNIT - IV: Applet and GUI Part I.

Fundamentals – applet class – life cycle – steps for applet


program – passing values through parameters – graphics – event handling; GUI I:GUI – creating
windows – dialog boxes – layout managers – AWT component classes – Swing component classes –
applications of AWT controls.

Applet and GUI Part I

Fundamentals

An applet is a special kind of Java program that runs in a Java enabled browser. This is the first Java
program that can run over the network using the browser. Applet is typically embedded inside a web
page and runs in the browser.

In other words, we can say that Applets are small Java applications that can be accessed on an Internet
server, transported over Internet, and can be automatically installed and run as apart of a web
document.

After a user receives an applet, the applet can produce a graphical user interface. It has limited access to
resources so that it can run complex computations without introducing the risk of viruses or breaching
data integrity.

To create an applet, a class must class extends [Link] class.

An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a plug-
in of the Web browser or a separate runtime environment to run an applet application.

JVM creates an instance of the applet class and invokes init() method to initialize an Applet.

Java Applet is deprecated since Java 9. It means Applet API is no longer considered important.

Lifecycle of Java Applet

Following are the stages in Applet

1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
import [Link].*;
import [Link].*;
public class Simple extends Applet
{
public void paint(Graphics g)
{
[Link]("A simple Applet", 20, 20);
}
}

Every Applet application must import two packages - [Link] and [Link].

[Link].* imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user
(either directly or indirectly) through the AWT. The AWT contains support for a window-based,
graphical user interface. [Link].* imports the applet package, which contains the class
Applet. Every applet that we create must be a subclass of Applet class.

The class in the program must be declared as public, because it will be accessed by code that is outside
the [Link] Applet application must declare a paint() method. This method is defined by AWT
class and must be overridden by the applet. The paint() method is called each time when an applet
needs to redisplay its output. Another important thing to notice about applet application is that, execution
of an applet does not begin at main() method. In fact an applet application does not have
any main() method.

Advantages of Applets
1. It takes very less response time as it works on the client side.
2. It can be run on any browser which has JVM running in it.

Applet class
Applet class provides all necessary support for applet execution, such as initializing and destroying of
applet. It also provide methods that load and display images and methods that load and play audio clips.

Applet Skeleton
import [Link].*;
import [Link].*;
public class AppletTest extends Applet
{
public void init() { //initialization }
public void start () { //start or resume execution }
public void stop() { //suspend execution }
public void destroy() { //perform shutdown activity }
public void paint (Graphics g) { //display the content of window }
}

Most applets override these four methods. These four methods forms Applet lifecycle.
 init() : init() is the first method to be called. This is where variable are initialized. This method is
called only once during the runtime of applet.
 start() : start() method is called after init(). This method is called to restart an applet after it has
been stopped.
 stop() : stop() method is called to suspend thread that does not need to run when applet is not
visible.
 destroy() : destroy() method is called when wer applet needs to be removed completely from
memory.
Note: The stop() method is always called before destroy() method.
Example

import [Link].*;
import [Link].*;
public class MyApplet extends Applet
{
int height, width;
public void init()
{
height = getSize().height;
width = getSize().width;
setName("MyApplet");
}
public void paint(Graphics g)
{
[Link](10, 30, 120, 120, 2, 3);
} }

Parameter in Applet

User-define Parameter can be applied in applet using <PARAM…> tags. Each <PARAM…> tag has a
name and value attribute.
Example:
name = color
Value = red

Syntax:
<PARAM name = ……… Value = “………” >

In an applet code, applet can refer to a parameter by its name and then find its value.

The two most important thing to handle and set up the parameter is the <PARAM> tag in the HTML
document and an applet code to parse this parameter.

init() method is used to get hold of the parameters which is defined in the <PARAM> tags. And
getParameter() method is used for getting the [Link] Applet, Parameters are passed
on applet when it is loaded.
[Link]
import [Link].*;
import [Link].*;
public class param extends Applet
{
String str;
public void init()
{
str=getParameter("pname");
if (str == null)
str = "Hello " + str;
}
public void paint(Graphics g)
{
[Link](str, 200, 200);
}
}
[Link]

<html>
<applet code=[Link] height=300
width=300>
<param Name="pname" value="Welcome ">
</applet>
</html>

Steps to run an Applet Program

An Applet program is compiled in the same way as we have been compiling wer console programs.
However there are two ways to run an applet.
 Executing the Applet within Java-compatible web browser.
 Using an Applet viewer, such as the standard tool, applet viewer. An applet viewer executes wer
applet in a window
For executing an Applet in an web browser, create short HTML file in the same directory.
Inside body tag of the file, include the following code. (applet tag loads the Applet class)

< applet code = "MyApplet" width=400 height=400 > < /applet >

Run the HTML file Running Applet using Applet Viewer


To execute an Applet with an applet viewer, write short HTML file as
discussed above. If we name it as [Link], then the following
command will run wer applet program.

f:/>appletviewer [Link]
Graphics in Applet

All graphics are drawn relative to a window. This can be the main window of an applet, a child window
of an applet, or a stand-alone application window. The origin of each window is at the top-left
Coordinates 0,0. Coordinates are specified in pixels. All output to a window takes place through a
graphics context. A graphics context is encapsulated by the Graphics class and is obtained in two ways:

1. It is passed to an applet when one of its various methods, such as paint() or update(), is called.
2. It is returned by the getGraphics( ) method of Component.

The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled.
Objects are drawn and filled in the currently selected graphics color, which is black by default. When a
graphics object is drawn that exceeds the dimensions of the window, the output is automatically clipped.

In Applet, [Link] provides methods for using graphics.

Below are the Methods of the Graphics class.

Sr
No. Methods Description

1 public abstract void drawString(String str, int x, int y) Used to draw specified string.

Used to draw a rectangle of specified width


2 public void drawRect(int x, int y, int width, int height)
and height.

Used to draw a rectangle with a default


3 public abstract void fillRect(int x, int y, int width, int height)
colourof specified width and height.

Used to draw oval of specified width and


4 public abstract void drawOval(int x, int y, int width, int height)
height.

Used to draw oval with a default colour of


5 public abstract void fillOval(int x, int y, int width, int height)
specified width and height.

Used for drawing lines between the point


6 public abstract void drawLine(int x1, int y1, int x2, int y2)
(x1, x1) and (x2, y2).

public abstract booleandrawImage(Image img, int x, int y,


7 Used for drawing a specified image.
ImageObserver observer)

public abstract void drawArc(int x, int y, int width, int height,


8 Used for drawing a circular arc.
intstartAngle, intarcAngle)

public abstract void fillArc(int x, int y, int width, int height,


9 Used for filling circular arc.
intstartAngle, intarcAngle)
10 public abstract void setColor(Color c) Used to set a colour to the object.

11 public abstract void setFont(Font font) Used to set font.

Example

import [Link]; Output


import [Link].*;
/*
<applet code="[Link]" width="300"
height="300"> </applet> */
public class GraphicsDemo extends Applet
{
public void paint (Graphics g)
{
[Link] ([Link]);
[Link] ("Welcome", 50, 50);
[Link] (20, 30, 20, 300);
[Link] (70, 100, 30, 30);
[Link] (170, 100, 30, 30);
[Link] (70, 200, 30, 30);
[Link] ([Link]);
[Link] (170, 200, 30, 30);
[Link] (90, 150, 30, 30, 30, 270);
[Link] (270, 150, 30, 30, 0, 180);
}
}

Event Handling

We perform event handling in Swing and AWT and we can also do it in Applets.

As we know, Graphical Programming Interfaces (GUIs) contain the components of the user interface. The
GUI components are responsible to generate events based on user interactions like clicking the mouse or
a key and so on. When an applet is designed, these events are captured and the appropriate actions are
performed in response to each of those events provided.

For handling events, we need event handlers, that must be available in Java. The procedure to be
followed when an event is generated is:
1. First, we must find the type of event that took place.
2. Now, find the component that generated the event.
3. Finally, we need the appropriate code that handles the event.
Button event handling

It is the most common event generating components in user interfaces. When we click on a button, an
action is generated. In fact, the term action is used in button event handling.
Properties

Some of the properties of a button event are:


 It manages the list of button objects that implement the ActionListener interface.
 The actionPerformed method is invoked when we click or press on a button, it is invoked for all
of the ActionListener instances in its list.
 The abstract actionPerformed method overrides the ActionListener classes to perform the task for
the button.
 As an argument of actionPerformed, an ActionEvent object is passed and from it we can extract
information about the event such as which ActionListener initiated the event.
 To add an instance of ActionListener to a button, we must invoke its
addActionListener(ActionListener) method.

Example

import [Link].*; Output


import [Link].*;
import [Link].*;
public class EventApplet extends Applet
implements ActionListener
{
Button bttn;
TextField txtfld;
public void init()
{
txtfld=new TextField();
[Link](35,45,250,30);
bttn=new Button("click me");
[Link](90,110,70,60);
add(bttn);add(txtfld);
[Link](this);
setLawet(null);
}
public void
actionPerformed(ActionEvent ae)
{
[Link]("welcome to Java");
}
}
/*
<applet code="[Link]"
width="400" height="400">
</applet
*/
GUI I:GUI

Reuse the graphics classes provided in JDK for constructing wer own Graphical User Interface
(GUI) applications. Writing wer own graphics classes (and re-inventing the wheels) is mission
impossible! These graphics classes, developed by expert programmers, are highly complex and involve
many advanced design patterns. However, re-using them are not so difficult, if we follow the API
documentation, samples and templates provided.

There are current three sets of Java APIs for graphics programming:

AWT (Abstract Windowing Toolkit), Swing and JavaFX.

1. AWT API was introduced in JDK 1.0. Most of the AWT UI components have become obsolete
and should be replaced by newer Swing UI components.

2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT,
was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC
consists of Swing, Java2D, Accessibility, Internationalization, and Pluggable Look-and-
Feel Support APIs. JFC has been integrated into core Java since JDK 1.2.

3. The latest JavaFX, which was integrated into JDK 8, was meant to replace Swing. JavaFX was
moved out from the JDK in JDK 11, but still available as a separate module.

AWT Packages

AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages of
737 classes as of JDK 8). Fortunately, only 2 packages - [Link] and [Link] - are
commonly-used.

1. The [Link] package contains the core AWT graphics classes:


 GUI Component classes, such as Button, TextField, and Label.
 GUI Container classes, such as Frame and Panel.
 Lawet managers, such as FlowLawet, BorderLawet and GridLawet.
 Custom graphics classes, such as Graphics, Color and Font.
2. The [Link] package supports event handling:
 Event classes, such as ActionEvent, MouseEvent, KeyEvent and WindowEvent,
 Event Listener Interfaces, such as ActionListener, MouseListener,
MouseMotionListener, KeyListener and WindowListener.
 Event Listener Adapter classes, such as MouseAdapter, KeyAdapter, and
WindowAdapter.

AWT provides a platform-independent and device-independent interface to develop graphic


programs that runs on all platforms, including Windows, macOS, and Unixes.
Creating Windows

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below, all the classes are available in [Link] package.

Component class
Component class is at the top of AWT hierarchy. It is an abstract class that encapsulates all the attributes
of visual component. A component object is responsible for remembering the current foreground and
background colors and the currently selected text font.

Container
Container is a component in AWT that contains another component like button, text field, tables
etc. Container is a subclass of component class. Container class keeps track of components that are
added to another component.

Panel
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu bar or border. It is
container that is used for holding components.

Window class
Window class creates a top level window. Window does not have borders and menubar.

Frame
Frame is a subclass of Window and have resizing canvas. It is a container that contain several different
components like button, title bar, textfield, label etc. In Java, most of the AWT applications are created
using Frame window. Frame class has two different constructors,

Frame() throws HeadlessException


Frame(String title) throws HeadlessException

Creating a Frame
There are two ways to create a Frame. They are,
 By Instantiating Frame class
 By extending Frame class
Creating Frame Window by Instantiating Frame class
import [Link].*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
//Creating a label
Label lb = new Label("welcome to java graphics");
[Link](lb); //adding label to the frame
[Link](300, 300); //setting frame size.
[Link](true); //set frame visibilty true
}
public static void main(String args[])
{
Testawt ta = new Testawt();
}
}

While creating a frame (either by instantiating or extending Frame class), Following two attributes
are must for visibility of the frame:

setSize(int width, int height);


setVisible(true);

When we create other components like Buttons, TextFields, etc. Then we need to add it to the frame by
using the method - add(Component's Object);
We can add the following method also for resizing the frame - setResizable(true);

Dialog Boxes

The main function of a dialog box is for an application or website to retrieve some input from
the user. That input can be an acknowledgment that they have read a message or something
they enter into a text area.

A dialog box immediately captures a user’s attention. It’s a perfect tool for collecting or
displaying important information.

Java is a diverse language that provides several classes to create dialog boxes. These classes include
JOptionPane, JDialog, and JFrame.

The JOptionPane Class


You can create a standard dialog box using one of several static methods belonging to the JOptionPane
class. These include:

 showMessageDialog(), which relays a message to the user.


 showConfirmDialog(), which asks a question that requires confirmation.
 showInputDialog(), which prompts a user for input.
 showOptionDialog(), which is a combination of the three other methods.
import [Link];
import [Link];
public class JOptionPaneApp {
JOptionPaneApp() {
JFrame frame = new JFrame();
[Link](frame,"This
is a JOptionPane message window.");
}
public static void main(String[] args)
{
new JOptionPaneApp();
}
}

Although JOptionPane provides standard dialog boxes, it has many options allowing you to tweak its
behavior. For example, the message dialog can take one of several types. The one above is an example
of an INFORMATION_MESSAGE, which is the default. The other message types are:

 ERROR_MESSAGE
 WARNING_MESSAGE
 QUESTION_MESSAGE
 PLAIN_MESSAGE

Example

ERROR_MESSAGE
[Link](frame, "This is a JOptionPane error message window.",
"Error", JOptionPane.ERROR_MESSAGE);

Layout Managers

A container has a so-called layout manager to arrange its components. The layout managers
provide a level of abstraction to map your user interface on all windowing systems, so that the
layout can be platform-independent.
AWT provides the following layout managers (in package [Link]):
FlowLayout, GridLawet, BorderLayout, GridBagLayout, BoxLayout, CardLayout, and others.

Container's setLayout() method

A container has a setLayout() method to set its layout manager:


// [Link]
public void setLayout(LayoutManager mgr)
To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you have to:

1. Construct an instance of the chosen layout object, via new and constructor, e.g., new
FlowLayout())

2. Invoke the setLayout() method of the Container, with the layout object created as the argument;

3. Place the GUI components into the Container using the add() method in the correct order; or into
the correct zones.
For example,
// Allocate a Panel (container)
Panel pnl = new Panel();
// Allocate a new Layout object. The Panel container sets to this layout.
[Link](new FlowLayout());
// The Panel container adds components in the proper order.
[Link](new JLabel("One"));
[Link](new JLabel("Two"));
[Link](new JLabel("Three"));
......

Container's getLayout() method


You can get the current layout via Container's getLayout() method.

Panel pnl = new Panel();


[Link]([Link]());//[Link][hgap=5,vgap=5,align=center]

Example – Flow Layout

import [Link].*;
import [Link].*;
// An AWT GUI program inherits the top-level container
[Link]
public class AWTFlowLayoutDemo extends Frame {
private Button btn1, btn2, btn3, btn4, btn5, btn6;
// Constructor to setup GUI components and event
//handlers
public AWTFlowLayoutDemo () {
setLayout(new FlowLayout());
// "super" Frame sets layout to FlowLayout, which
//arranges the components
// from left-to-right, and flow from top-to-bottom.
btn1 = new Button("Button 1"); add(btn1);
btn2 = new Button("This is Button 2"); add(btn2);
btn3 = new Button("3"); add(btn3);
btn4 = new Button("Another Button 4"); add(btn4);
btn5 = new Button("Button 5"); add(btn5);
btn6 = new Button("One More Button 6"); add(btn6);
// "super" Frame sets title
setTitle("FlowLayout Demo"); setSize(280, 150);
setVisible(true); }
public static void main(String[] args) {
new AWTFlowLayoutDemo(); }}

135 Department of Computer Science | Valluvar College of Science and Management,Karur


AWT Component Classes

AWT provides many ready-made and reusable GUI components in package [Link]. The
frequently-used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List,
and Choice, as illustrated below.

AWT GUI Component: [Link]

A [Link] provides a descriptive text string. Take note that [Link]() prints to the
system console, NOT to the graphics screen. You could use a Label to label another component (such as
text field) to provide a text description.

Check the JDK API specification for [Link].

Constructors

// Construct a Label with the given text String, of the text alignment

public Label(String strLabel, int alignment);

public Label(String strLabel); // Construct a Label with the given text String

public Label(); // Construct an initially empty Label

The Label class has three constructors:

The first constructor constructs a Label object with the given text string in the given
alignment. Note that three static constants [Link], [Link], and [Link] are
defined in the class for we to specify the alignment (rather than asking you to memorize arbitrary integer
values).
The second constructor constructs a Label object with the given text string in default of left-
aligned.

The third constructor constructs a Label object with an initially empty string. You could set the
label text via the setText() method later.

Constants (final static fields)

public static final LEFT; // [Link]


public static final RIGHT; // [Link]
public static final CENTER; // [Link]

Public Methods

// Examples
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment); // [Link], [Link], [Link]

The getText() and setText() methods can be used to read and modify the Label's text. Similarly, the
getAlignment() and setAlignment() methods can be used to retrieve and modify the alignment of the
text.

Constructing a Component and Adding the Component into a Container

Three steps are necessary to create and place a GUI component:

 Declare the component with an identifier (name);


 Construct the component by invoking an appropriate constructor via the new operator;
 Identify the container (such as Frame or Panel) designed to hold this component. The
container can then add this component onto itself via [Link](aComponent) method.
Every container has a add(Component) method. Take note that it is the container that actively
and explicitly adds a component onto itself, NOT the other way.

Example

Label lblInput; // Declare an Label instance called lblInput

// Construct by invoking a constructor via the new operator


lblInput = new Label("Enter ID");

// [Link](lblInput) - "this" is typically a subclass of Frame


add(lblInput);

[Link]("Enter password"); // Modify the Label's text string

[Link](); // Retrieve the Label's text string


AWT GUI Component: [Link]

A [Link] is a GUI component that triggers a certain programmed action upon clicking.

Constructors

public Button(String btnLabel);


// Construct a Button with the given label
public Button();
// Construct a Button with empty label

The Button class has two constructors. The first constructor creates a Button object with the given
label painted over the button. The second constructor creates a Button object with no label.

Public Methods

public String getLabel(); // Get the label of this Button instance

public void setLabel(String btnLabel); // Set the label of this Button instance

public void setEnable(boolean enable); // Enable or disable this Button. Disabled


Button cannot be clicked.

The getLabel() and setLabel() methods can be used to read the current label and modify the label of a
button, respectively.

Event

Clicking a button fires a so-called ActionEvent and triggers a certain programmed action. I will explain
event-handling later.

Example

// Declare and allocate a Button instance called btnColor


Button btnColor = new Button("Red");
add(btnColor); // "this" Container adds the Button
...
[Link]("Green"); // Change the button's label
[Link](); // Read the button's label

AWT GUI Component: [Link]


A [Link] is single-line text box for users to enter texts. (There is a multiple-line text box
called TextArea.) Hitting the "ENTER" key on a TextField object fires an ActionEvent.

Constructors

public TextField(String initialText, int columns);


// Construct a TextField instance with the given initial text string with the
number of columns.

public TextField(String initialText);


// Construct a TextField instance with the given initial text string.
public TextField(int columns); // Construct a TextField instance with the number of
columns.

Public Methods

public String getText();


// Get the current text on this TextField instance
public void setText(String strText);
// Set the display text on this TextField instance
public void setEditable(boolean editable);
// Set this TextField to editable (read/write) or non-editable (read-only)

Event
Hitting the "ENTER" key on a TextField fires a ActionEvent, and triggers a certain programmed action.

Example
TextField tfInput = new TextField(30); // Declare and allocate an TextField instance
called tfInput

add(tfInput); // "this" Container adds the TextField

TextField tfResult = new TextField(); // Declare and allocate an TextField instance


called tfResult

[Link](false) ; // Set to read-only

add(tfResult); // "this" Container adds the TextField


......

// Read an int from TextField "tfInput", square it, and display on "tfResult".
// getText() returns a String, need to convert to int
int number = [Link]([Link]());

number *= number;

// setText() requires a String, need to convert the int number to String.

[Link](number + "");
Swing Components
Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing
window-based applications. Java Swing is lightweight and platform-independent that
contains various components and container classes. Furthermore, the Java swing library is built on
the top of the AWT(Abstract Window Toolkit), an API completely written in Java. In every
application, users can find an interactive and user-friendly interface that gives them the freedom to use
the app.

In Java Swing, there are several components like a scroll bar, button, text field, text area,
checkbox, radio button, etc. These components jointly form a GUI that offers a rich set of
functionalities and allows high-level customization.

A component is independent visual control, and Java Swing Framework contains a large set of these
components, providing rich functionalities and allowing high customization. They all are derived from
JComponent class. All these components are lightweight components. This class offers some standard
functionality like pluggable look and feel, support for accessibility, drag and drop, layout, etc.
A container holds a group of components. It delivers a space where a component can be managed and
displayed. Containers are of two types:

It inherits the Component and Container of AWT.

We cannot contain it within other containers.


Top-level Containers
Heavyweight.

Example: JFrame, JDialog, JApplet

It inherits JComponent class.

It is a general-purpose container.
Lightweight
Containers We can use it to organize related components
together.

Example: JPanel
JButton
We use JButton class to create a push button on the UI. The button can include some display text or
images. It yields an event when clicked and double-clicked. We can implement a JButton in the
application by calling one of its constructors.

Syntax:
JButton okBtn = new JButton(“Click”); This constructor returns a button with the text Click on it.

JButton homeBtn = new JButton(carIcon); Returns a button with a car Icon on it.

JButton homeBtn2 = new JButton(carIcon, “Car”); Returns a button with the car icon and text
as Car.
JLabel
We use JLabel class to render a read-only text label or images on the UI. It does not generate any event.
Syntax:
JLabel textLabel = new JLabel(“This is 1st L...”);

This constructor returns a label with specified text.


JLabel imgLabel = new JLabel(carIcon);

It returns a label with a car icon.

The JLabel Contains four constructors. They are as follows:


1. JLabel()
2. JLabel(String s)
3. JLabel(Icon i)
4. JLabel(String s, Icon i, int horizontalAlignment)

Display:

JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted text in the box. We
can initialize the text field by calling its constructor and passing an optional integer parameter. This
parameter sets the box width measured by the number of columns. Also, it does not limit the number of
characters that can be input into the box.
Syntax:

JTextField txtBox = new JTextField(50);

It is the most widely used text component. It has three constructors:


1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)

Note: cols represent the number of columns in the text field.


Display:

JCheckBox
The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on and off. On
selecting, the state is set to "on," and a small tick is displayed inside the box.

Syntax:
CheckBox chkBox = new JCheckBox(“Java Swing”, true);

It returns a checkbox with the label Pepperoni pizza. Notice the second parameter in the constructor. It is
a boolean value that denotes the default state of the check-box. True means the check-box defaults to
the "on" state.
Display:

JRadioButton
A radio button is a group of related buttons from which we can select only one. We use JRadioButton
class to create a radio button in Frames and render a group of radio buttons in the UI. Users can select
one choice from the group.

Syntax:
JRadioButton jrb = new JRadioButton("Easy");

Display:

JComboBox
The combo box is a combination of text fields and a drop-down list. We use JComboBox component to
create a combo box in Swing.

Syntax:
JComboBox jcb = new JComboBox(name);

Display:

JTextArea
In Java, the Swing toolkit contains a JTextArea Class. It is under package [Link] class. It
is used for displaying multiple-line text.

Declaration:
public class JTextArea extends JTextComponent
Syntax:

JTextArea textArea_area=new JTextArea("Ninja! please write something in the text


area.");

The JTextArea Contains four constructors. They are as follows:


1. JTextArea()
2. JTextArea(String s)
3. JTextArea(int row, int column)
4. JTextArea(String s, int row, int column)

Display:

Difference between AWT and Swing

Java AWT Java Swing

Java swing components are platform-


AWT components are platform-dependent.
independent.

AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.

Swing provides more powerful


components such as tables, lists,
AWT provides less components than Swing.
scrollpanes, colorchooser, tabbedpane
etc.

AWT doesn't follows MVC(Model View Controller) where


model represents data, view represents presentation
Swing follows MVC.
and controller acts as an interface between model and
view.
applications of AWT controls

Java Program to Design Login Window Using AWT Controls(Button,Label,Textfield)


import [Link].*;
import [Link].*;
class MyLoginWindow extends Frame
{
TextField name,pass;
Button b1,b2;
MyLoginWindow()
{
setLayout(new FlowLayout());
[Link](null);
Label n=new Label("Name:",[Link]);
Label p=new Label("password:",[Link]);
name=new TextField(20);
pass=new TextField(20);
[Link]('#');
b1=new Button("submit");
b2=new Button("cancel");
[Link](n);
[Link](name);
[Link](p);
[Link](pass);
[Link](b1);
[Link](b2);
[Link](70,90,90,60);
[Link](70,130,90,60);
[Link](200,100,90,20);
[Link](200,140,90,20);
[Link](100,260,70,40);
[Link](180,260,70,40);

}
public static void main(String args[])
{
MyLoginWindow ml=new MyLoginWindow();
[Link](true);
[Link](400,400);
[Link]("my login window");

}
}
UNIT – V : GUI Part II and Java Database Connectivity Event handling – AWT components –
AWT graphics classes – Swing controls – application using Swing and AWT; Java Database Connectivity:
types of drivers – JDBC architecture – JDBC classes & interfaces – steps in JDBC applications – creating a
new Database and table with JDBC.

AWT components

AWT Components

1. Containers

Container in Java AWT is a component that is used to hold other components such as text fields, buttons,
etc. It is a subclass of [Link] and is responsible for keeping a track of components being
added. There are four types of containers provided by AWT in Java.
Types of Containers
1. Window: It is an instance of the Window class having neither border nor title. It is used for
creating a top-level window.
2. Frame: Frame is a subclass of Window and contains title, border and menu bars. It comes with
a resizing canvas and is the most widely used container for developing AWT applications. It is
capable of holding various components such as buttons, text fields, scrollbars, etc. You can
create a Java AWT Frame in two ways:
i. By Instantiating Frame class
ii. By extending Frame class
3. Dialog: Dialog class is also a subclass of Window and comes with the border as well as the title.
Dialog class’s instance always needs an associated Frame class instance to exist.
4. Panel: Panel is the concrete subclass of Container and doesn’t contain any title bar, menu bar or
border. Panel class is a generic container for holding the GUI components. You need the instance
of the Panel class in order to add the components.
2. Button

[Link] class is used to create a labeled button. GUI component that triggers a certain
programmed action upon clicking it. The Button class has two constructors:

//Construct a Button with the given label


public Button(String btnLabel);

//Construct a Button with empty label


public Button();
A few of the methods provided by this class have been listed below:

//Get the label of this Button instance


public String getLabel();

//Set the label of this Button instance


public void setLabel(String btnLabel);

//Enable or disable this Button. Disabled Button cannot be clicked


public void setEnable(boolean enable);

3. Text Field

A [Link] class creates a single-line text box for users to enter texts. The TextField class has
three constructors which are:
//Construct a TextField instance with the given initial text string with the number
of columns.
public TextField(String initialText, int columns);

//Construct a TextField instance with the given initial text string.


public TextField(String initialText);

//Construct a TextField instance with the number of columns.


public TextField(int columns);
A few of the methods provided by TextField class are:

// Get the current text on this TextField instance


public String getText();

// Set the display text on this TextField instance


public void setText(String strText);
//Set this TextField to editable (read/write) or non-editable (read-only)
public void setEditable(boolean editable);

4. Label

The [Link] class provides a descriptive text string that is visible on GUI. An AWT Label object is a
component for placing text in a container. Label class has three constructors which are:

// Construct a Label with the given text String, of the text alignment
public Label(String strLabel, int alignment);

//Construct a Label with the given text String


public Label(String strLabel);

//Construct an initially empty Label


public Label();
This class also provides 3 constants which are:

public static final LEFT; // [Link]

public static final RIGHT; // [Link]

public static final CENTER; // [Link]


Below I have listed down the public methods provided by this class:

public String getText();

public void setText(String strLabel);

public int getAlignment();

//[Link], [Link], [Link]


public void setAlignment(int alignment);
5. Canvas
A Canvas class represents the rectangular area where you can draw in an application or receive inputs
created by the user.

6. Choice
Choice class is used to represent a pop-up menu of choices. The selected choice is shown on the top of
the given menu.

7. Scroll Bar
The Scrollbar class object is used to add horizontal and vertical scrollbar in the GUI. It enables a user to
see the invisible number of rows and columns.

8. List
The object of List class represents a list of text items. Using the List class a user can choose either one
item or multiple items.

9. CheckBox
The Checkbox is a class is a graphical component that is used to create a checkbox. It has two state
options; true and false. At any point in time, it can have either of the two.

import [Link];
// import awt and its subclasses
import [Link].*;
// class extending applet
public class AWTDemo extends Applet {
// this method gets automatically called
public void init() {
Button button = new Button("Click Here to Submit"); // creating a button
[Link](button); // adding button to container
Checkbox checkbox = new Checkbox("My Checkbox"); // creating a checkbox
[Link](checkbox); //adding checkbox to container
CheckboxGroup checkboxgrp = new CheckboxGroup(); // creating checkbox group
[Link](new Checkbox("Check box Option 1", checkboxgrp, false));
[Link](new Checkbox("Check box Option 2", checkboxgrp, false));
[Link](new Checkbox("Check box Option 3", checkboxgrp, true));
// adding to container
Choice choice = new Choice(); // creating a choice
[Link]("Choice Option 1");
[Link]("Choice Option 2");
[Link]("Choice Option 3");
[Link](choice); //adding choice to container
Label label = new Label("Demo Label"); // creating a label
[Link](label); //adding label to container
TextField textfield = new TextField("Demo TextField", 30); // creating a Textfield
[Link](textfield); // adding Textfield to container
}
}
//OUTPUT
AWT graphics classes

The Graphics class is the abstract super class for all graphics contexts which allow an application
to draw onto components that can be realized on various devices, or onto off-screen images as well.
A Graphics object encapsulates all state information required for the basic rendering
operations that Java supports. State information includes the following properties.
 The Component object on which to draw.
 A translation origin for rendering and clipping coordinates.
 The current clip.
 The current color.
 The current font.
 The current logical pixel operation function.
 The current XOR alternation color

Class declaration

Following is the declaration for [Link] class:

public abstract class Graphics extends Object

Class constructors

S.N. Constructor & Description

1 Graphics() ()

Constructs a new Graphics object.

They are totally 50 methods are available in Graphics classes

1. abstract void clearRect(int x, int y, int width, int height) - Clears the specified rectangle
by filling it with the background color of the current drawing surface.
2. abstract void clipRect(int x, int y, int width, int height) - Intersects the current clip with
the specified rectangle.
3. abstract void copyArea(int x, int y, int width, int height, int dx, int dy) - Copies an area
of the component by a distance specified by dx and dy.
4. abstract Graphics create() - Creates a new Graphics object that is a copy of this Graphics
object.
5. Graphics create(int x, int y, int width, int height) - Creates a new Graphics object based on
this Graphics object, but with a new translation and clip area.
6. abstract void dispose() - Disposes of this graphics context and releases any system resources
that it is using.
7. void draw3DRect(int x, int y, int width, int height, boolean raised) - Draws a 3-D
highlighted outline of the specified rectangle.
8. abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) -
Draws the outline of a circular or elliptical arc covering the specified rectangle.
9. void drawBytes(byte[] data, int offset, int length, int x, int y) - Draws the text given by
the specified byte array, using this graphics context's current font and color.
10. void drawChars(char[] data, int offset, int length, int x, int y) - Draws the text given by
the specified character array, using this graphics context's current font and color.
11. abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver
observer) - Draws as much of the specified image as is currently available.
12. abstract boolean drawImage(Image img, int x, int y, ImageObserver observer) -
Draws as much of the specified image as is currently available.
13. abstract boolean drawImage(Image img, int x, int y, int width, int height, Color
bgcolor, ImageObserver observer) - Draws as much of the specified image as has already
been scaled to fit inside the specified rectangle.
14. abstract boolean drawImage(Image img, int x, int y, int width, int height,
ImageObserver observer) - Draws as much of the specified image as has already been scaled
to fit inside the specified rectangle.
15. abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) - Draws as much of the
specified area of the specified image as is currently available, scaling it on the fly to fit inside the
specified area of the destination drawable surface.
16. abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int
sy1, int sx2, int sy2, ImageObserver observer) - Draws as much of the specified area of
the specified image as is currently available, scaling it on the fly to fit inside the specified area of
the destination drawable surface.
17. abstract void drawLine(int x1, int y1, int x2, int y2) - Draws a line, using the current color,
between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system.
18. abstract void drawOval(int x, int y, int width, int height) - Draws the outline of an oval.
19. abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) - Draws a closed
polygon defined by arrays of x and y coordinates.
20. void drawPolygon(Polygon p) - Draws the outline of a polygon defined by the specified
Polygon object.
21. abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) - Draws a sequence
of connected lines defined by arrays of x and y coordinates.
22. void drawRect(int x, int y, int width, int height) - Draws the outline of the specified
rectangle.
23. abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight) - Draws an outlined round-cornered rectangle using this graphics context's current
color.
24. abstract void drawString(AttributedCharacterIterator iterator, int x, int y) - Renders
the text of the specified iterator applying its attributes in accordance with the specification of the
TextAttribute class.
25. abstract void drawString(String str, int x, int y) - Draws the text given by the specified
string, using this graphics context's current font and color.
26. void fill3DRect(int x, int y, int width, int height, boolean raised) - Paints a 3-D
highlighted rectangle filled with the current color.
27. abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) -
Fills a circular or elliptical arc covering the specified rectangle.
28. abstract void fillOval(int x, int y, int width, int height) - Fills an oval bounded by the
specified rectangle with the current color.
29. abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) - Fills a closed polygon
defined by arrays of x and y coordinates.
30. void fillPolygon(Polygon p) - Fills the polygon defined by the specified Polygon object with
the graphics context's current color.
31. abstract void fillRect(int x, int y, int width, int height) - Fills the specified rectangle.
32. abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight) - Fills the specified rounded corner rectangle with the current color.
33. void finalize() - Disposes of this graphics context once it is no longer referenced.
34. abstract Shape getClip() - Gets the current clipping area.
35. abstract Rectangle getClipBounds() - Returns the bounding rectangle of the current clipping
area.
36. Rectangle getClipBounds(Rectangle r) - Returns the bounding rectangle of the current
clipping area.
37. Rectangle getClipRect() - Deprecated. As of JDK version 1.1, replaced by getClipBounds().
38. abstract Color getColor() - Gets this graphics context's current color.
39. abstract Font getFont() - Gets the current font.
40. FontMetrics getFontMetrics() - Gets the font metrics of the current font.
41. abstract FontMetrics getFontMetrics(Font f) - Gets the font metrics for the specified font.
42. boolean hitClip(int x, int y, int width, int height) - Returns true if the specified rectangular
area might intersect the current clipping area.
43. abstract void setClip(int x, int y, int width, int height) - Sets the current clip to the
rectangle specified by the given coordinates.
44. abstract void setClip(Shape clip) - Sets the current clipping area to an arbitrary clip shape.
45. abstract void setColor(Color c) - Sets this graphics context's current color to the specified
color.
46. abstract void setFont(Font font) - Sets this graphics context's font to the specified font.
47. abstract void setPaintMode() - Sets the paint mode of this graphics context to overwrite the
destination with this graphics context's current color.
48. abstract void setXORMode(Color c1) - Sets the paint mode of this graphics context to
alternate between this graphics context's current color and the new specified color.
49. String toString() - Returns a String object representing this Graphics object's value.
50. abstract void translate(int x, int y) - Translates the origin of the graphics context to the
point (x, y) in the current coordinate system.
application using Swing and AWT

AWT

import [Link].*;
public class AwtApp extends Frame {
AwtApp(){
Label firstName = new Label("First Name");
[Link](20, 50, 80, 20);

Label lastName = new Label("Last Name");


[Link](20, 80, 80, 20);

Label dob = new Label("Date of Birth");


[Link](20, 110, 80, 20);

TextField firstNameTF = new TextField();


[Link](120, 50, 100, 20);

TextField lastNameTF = new TextField();


[Link](120, 80, 100, 20);

TextField dobTF = new TextField();


[Link](120, 110, 100, 20);

Button sbmt = new Button("Submit");


[Link](20, 160, 100, 30);
Button reset = new Button("Reset");
[Link](120,160,100,30);

add(firstName); add(lastName);
add(dob); add(firstNameTF);
add(lastNameTF); add(dobTF);
add(sbmt); add(reset);

setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
AwtApp awt = new AwtApp();
}
}
Swing
import [Link].*;
public class JComboBoxDemo
{
JFrame f;
JComboBoxDemo ()
{
f = new JFrame ("ComboBox Example");
String country[] ={ "Hyderabad", "Chennai", "Bengaluru",
"Mumbai", "Delhi" };
JComboBox cb = new JComboBox (country);
[Link] (50, 50, 90, 20);
[Link] (cb);
[Link] (null);
[Link] (400, 500);
[Link] (true);
}
public static void main (String[]args)
{
new JComboBoxDemo ();
}
}

Java Database Connectivity (JDBC)

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database. 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:

 JDBC-ODBC Bridge Driver,


 Native Driver,
 Network Protocol Driver, and
 Thin Driver

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 [Link] package contains classes and interfaces for JDBC API.
A list of popular interfaces of JDBC API are given below:

 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface

A list of popular classes of JDBC API are given below:

 DriverManager class
 Blob class
 Clob class
 Types class

Use of JDBC

Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which 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.

Types of Drivers

DBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:

 JDBC-ODBC bridge driver


 Native-API driver (partially java driver)
 Network Protocol driver (fully java driver)
 Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge
driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin
driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC
drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:
 easy to use.
 can be easily connected to any database.
Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC function calls.
 The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.

Advantage:
 performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
 The Native driver needs to be installed on the each client machine.
 The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:

 No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

Disadvantages:

 Network support is required on client machine.


 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is
known as thin driver. It is fully written in Java language.

Advantage:
 Better performance than all other drivers.
 No software is required at client side or server side.
Disadvantage:
 Drivers depend on the Database.

JDBC architecture

Two-Tier Architecture

A Java applet or application communicates directly with the data source in the two-tier paradigm. This
necessitates the use of a JDBC driver that can interface with the data source in question. The user’s
commands are transmitted to the database or other data source, and the statements’ results are returned
to the user. The data source could be on another machine to which the user has a network connection. A
client/server configuration is one in which the user’s machine acts as the client and the system that
houses the data source acts as the server. An intranet, for example, can connect people within a
company, or the Internet can be used as the network.

Three-Tier Architecture

Commands are sent to a “middle tier” of services in the three-tier paradigm, which subsequently
transmits the commands to the data source. The data source interprets the commands and provides the
results to the middle tier, which ultimately passes them on to the user. The three-tier architecture
appeals to MIS directors because the intermediate tier allows them to maintain control over access and
the types of changes that can be made to company data. Another benefit is that it makes application
deployment easier. Finally, the three-tier architecture can bring performance benefits in many
circumstances.
The components of JDBC are listed below. These elements assist us in interacting with a database.
The following are the JDBC components:

1. JDBC Driver Manager: In a JDBC application, the Driver Manager loads database-specific
drivers. This driver manager makes a database connection. To handle the user request, it
additionally makes a database-specific call to the database.

2. Driver: A driver is an interface that manages database server connectivity. Communication is


handled using DriverManager objects.

3. JDBC-ODBC Bridge Drivers: They are used to link database drivers to the database. The JDBC
method calls are translated into ODBC method calls by the bridge. To access the ODBC (Open
Database Connectivity) characteristics, it uses the [Link] package, which includes the
native library.

4. JDBC API: Sun Microsystem has provided JDBC API, which allows you to write a Java program
that talks with any database without modifying the code. The JDBC API is implemented by the
JDBC Driver.

5. JDBC Test Suite: The JDBC Test Suite aids in the testing of JDBC Driver operations such as
insertion, deletion, and updating. It aids in determining whether or not the JDBC Drivers will run
the program. It ensures that the program will be run by JDBC Drivers with confidence and
conformity.

6. Database Server: This is the database server that the JDBC client wants to communicate with,
such as Oracle, MySQL, SQL Server, and so on.

7. Statement: To send SQL statements to the database, you use objects built using this interface.
In addition to performing stored procedures, certainly derived interfaces accept parameters.

8. RuleSet: These objects retain data retrieved from a database when you use Statement objects
to conduct a SQL query. It functions as an iterator, allowing you to cycle through the data it
contains.
9. SQL Exception: This class is responsible for any errors that occur in a database application.

Advantages of JDBC Architecture

 It can read any database. The only condition for it to do so is that all of the drivers be properly
installed.
 It pulls information from a database and converts it to XML.
 It does not necessitate the conversion of the content.
 Software maintenance is centralized with no client settings necessary. Because the driver is built
in Java, the JDBC URL or a DataSource object has all of the information required to establish a
connection.
 It supports queries and stored procedures completely.
 The JDBC API contains a DataSource object that can be used to identify and connect to a data
source. This improves the code’s portability and maintainability.
 Both synchronous and asynchronous processing is supported.
 The Java API and the JDBC API work together to make application development simple and cost-
effective.
 Modules are supported.
 Even if data is housed on various database management systems, businesses can continue to use
their installed databases and access information.

classes and interfaces of JDBC

JDBC API is available in two packages [Link], core API and [Link] JDBC optional packages.
Following are the important classes and interfaces of JDBC.

Class/interface Description

DriverManager This class manages the JDBC drivers. You need to register your drivers to
[Link] provides methods such as registerDriver() and getConnection().

Driver This interface is the Base interface for every driver class i.e. If you want to
create a JDBC Driver of your own you need to implement this interface. If
you load a Driver class (implementation of this interface), it will create an
instance of itself and register with the driver manager.

Statement This interface represents a static SQL statement. Using the Statement object
and its methods, you can execute an SQL statement and get the results of
[Link] provides methods such as execute(), executeBatch(), executeUpdate()
Class/interface Description

etc. To execute the statements.

PreparedStatement This represents a precompiled SQL statement. An SQL statement is compiled


and stored in a prepared statement and you can later execute this multiple
times. You can get an object of this interface using the method of the
Connection interface named prepareStatement(). This provides methods such
as executeQuery(), executeUpdate(), and execute() to execute the prepared
statements and getXXX(), setXXX() (where XXX is the datatypes such as long
int float etc..) methods to set and get the values of the bind variables of the
prepared statement.

CallableStatement Using an object of this interface you can execute the stored procedures. This
returns single or multiple results. It will accept input parameters too. You can
create a CallableStatement using the prepareCall() method of the Connection
[Link] like Prepared statement, this will also provide setXXX() and
getXXX() methods to pass the input parameters and to get the output
parameters of the procedures.

Connection This interface represents the connection with a specific database. SQL
statements are executed in the context of a [Link] interface
provides methods such as close(), commit(), rollback(), createStatement(),
prepareCall(), prepareStatement(), setAutoCommit() setSavepoint() etc.

ResultSet This interface represents the database result set, a table which is generated
by executing statements. This interface provides getter and update methods
to retrieve and update its contents respectively.

ResultSetMetaData This interface is used to get the information about the result set such as,
number of columns, name of the column, data type of the column, schema of
the result set, table name, etcIt provides methods such as
getColumnCount(), getColumnName(), getColumnType(), getTableName(),
getSchemaName() etc.

Steps in JDBC applications

There are 5 steps to connect any java application with the database using JDBC. These steps are as
follows:
 Register the Driver class
 Create connection
 Create statement
 Execute queries
 Close connection

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method

public static void forName(String className) throws ClassNotFoundException

Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's Jar in the
classpath, and then JDBC driver manager can detect and load the driver automatically.

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

[Link]("[Link]");

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method

1) public static Connection getConnection(String url) throws SQLException

2) public static Connection getConnection(String url,String name,String password)

throws SQLException

Example to establish connection with the Oracle database

Connection
con=[Link]("jdbc:oracle:thin:@localhost:1521:xe","system","passw
ord");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException


Example to create the statement object

Statement stmt=[Link]();

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the


database. This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=[Link]("select * from emp");
while([Link]()){
[Link]([Link](1)+" "+[Link](2));
}

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.

Syntax of close() method


public void close() throws SQLException
Example to close connection
[Link]();

Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to follow 5 following steps.

In this example we are using MySql as the database. So we need to know following informations for the
mysql database:

Driver class: The driver class for the mysql database is [Link].

Connection URL: The connection URL for the mysql database is


jdbc:mysql://localhost:3306/employee where jdbc is the API, mysql is the database, localhost is
the server name on which mysql is running, we may also use IP address, 3306 is the port number and
sonoo is the database name. We may use any database, in such case, we need to replace the sonoo with
our database name.

Username: The default username for the mysql database is root.

Password: It is the password given by the user at the time of installing the mysql database. In this
example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create database
first.

create database employee;


use employee;
create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database


In this example, employee is the database name, root is the username and password both

import [Link].*;
class MysqlCon{
public static void main(String args[]){
try{

[Link]("[Link]");

Connection con=[Link](
"jdbc:mysql://localhost:3306/employee","root","root");

Statement stmt=[Link]();

ResultSet rs=[Link]("select * from emp");


while([Link]())
[Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
[Link]();
}catch(Exception e){ [Link](e);}
}
}

You might also like