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

OOP JAVA M5 Ktunotes - in

Uploaded by

Sneha Tiwari
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)
18 views

OOP JAVA M5 Ktunotes - in

Uploaded by

Sneha Tiwari
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
You are on page 1/ 221

CST 205 Object Oriented Programming using Java

(As per KTU 2019 Syllabus)

Module 5

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
5.1 - Swing fundamentals, Key features
SWING vs AWT

SWING Features

● Light weight components


● PLAF
● Transparent controls

Downloaded from Ktunotes.in


User Interface (UI)
● The user interface (UI) is the point at which human users interact with a
computer.
● In software development UI signifies the ways in which your software can
interact with the human user (through inputs and outputs)
● There are 2 types of user interfaces CUI - Character UI and GUI - Graphical UI

Downloaded from Ktunotes.in


Graphical User Interface Development
There are multiple ways to develop GUI based applications in java, out of which the most popular ones
are AWT and Swing classes. Both packages contains UI controls such as Button, TextField etc.

1. AWT
AWT stands for Abstract Window Toolkit.
It is a platform-dependent API to develop GUI (Graphical User Interface) or window-based applications
in Java.
It was developed by Sun Microsystems In 1995.
It is heavy-weight in use because it is generated by the system’s host operating system.
It contains a large number of classes and methods, which are used for creating and managing GUI.

2. Swing:
Swing is a lightweight Java graphical user interface (GUI) that is used to create various applications.
Swing has components which are platform-independent.
Swing includes packages for creating desktop applications in Java.
Swing components are written in Java language. It is a part of Java Foundation Classes(JFC).
Downloaded from Ktunotes.in
Swing
Swing is a set of program
components for Java programmers
that provide the ability to create
graphical user interface ( GUI )
components, such as buttons and
scroll bars, that are independent of
the windowing system for specific
operating system .

It is present in javax.swing package.

Downloaded from Ktunotes.in


Swing fundamentals
• Swing is written entirely in Java (platform-independent).
– So swing components are lightweight
– Swing components are NOT implemented by platform specific code.
• Swing is a set of classes.
• Swing is built on the foundation of the AWT(Abstract Window Toolkit).
• Swing provides more powerful and flexible functionalities than standard AWT
components.
• Swing classes are defined in javax.swing package and its subpackages.

Downloaded from Ktunotes.in


Swing Key Features
Two key features of Swing are
– Swing components are Lightweight
– Swing supports a Pluggable Look and Feel (PLAF)

Downloaded from Ktunotes.in


Features - Swing components are Lightweight
Swing Components are lightweight because
– they are written entirely in Java
– they do not map directly to platform-specific peers.
Peer classes are written by java API developers to interface with native objects
– Lightweight components do not call the native operating system for drawing the
graphical user interface(GUI) components
– They are rendered using graphics primitives
They can be transparent, which enables non rectangular shapes.
– lightweight components are more efficient and more flexible.

Downloaded from Ktunotes.in


Features - Swing components are Lightweight
Lightweight components
– do not translate into native peers,
– the look and feel of each component is determined by Swing, not by the
underlying operating system.
• This means that each component will work in a consistent manner across all
platforms.

Downloaded from Ktunotes.in


Look and Feel
“Look” refers to the appearance of GUI widgets and “feel” refers to the way the
widgets behave.

1. Motif
2. Nimbus
3. System
4. Metal (Cross
platform)
5. ...

Downloaded from Ktunotes.in


Feature - Swing Supports a Pluggable Look and
Feelsupports a pluggable look and feel (PLAF).
Swing
– Because each Swing component is rendered by Java code not by native peers,
the look and feel of a component is under the control of Swing.
It is possible to separate the look and feel of a component from the logic of the
component.
Advantage:
– It is possible to change the way that a component is rendered without affecting
any of its other aspects
• it is possible to “plug in” a new look and feel for any given component without
creating any side effects in the code that uses that component.
Downloaded from Ktunotes.in
Feature - Swing Supports a Pluggable Look and
It Feel
is possible to define entire sets of look-and-feels that represent different GUI
styles. To use a specific style, its look and feel is simply “plugged in.”
– Once this is done, all components are automatically rendered using that style.
Pluggable look-and-feels offer several important advantages.
– It is possible to define a look and feel that is consistent across all platforms.
– it is possible to create a look and feel that acts like a specific platform.
• For example, if you know that an application will be running only in a Windows
environment, it is possible to specify the Windows look and feel.
• It is also possible to design a custom look and feel. Finally, the look and feel can
be changed dynamically at run time.
Downloaded from Ktunotes.in
Feature - Swing Supports a Pluggable Look and
Feel

Downloaded from Ktunotes.in


Difference between Swing and AWT

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
5.2 - MVC, Swing controls, Components & Containers
Overview of the contents

● Model View Control (MVC) Design Pattern


● Swing controls
● Component
● Containers

Downloaded from Ktunotes.in


5.2 - Design Pattern - MVC
● In software engineering, a design pattern is a general repeatable solution to
a commonly occurring problem in software design.
● It is a generalised description or template for how to solve a problem that can
be used in many different situations.

Model View Controller(MVC) is a software design pattern commonly used for


developing User interface that divides the related program logic into three
interconnected elements.

1. Model
2. View
3. Controller

Downloaded from Ktunotes.in


5.2 - MVC
A visual component is a composite of three
distinct aspects:

– The state information associated with the


component MODEL

– The way that the component looks when


rendered on the screen VIEW [look]

– The way that the component reacts to


CONTROLLER [feel]

MVC (Model View Controller) architecture is


successful because each piece of the design
corresponds to an aspect of a component.

Downloaded from Ktunotes.in


5.2 - MVC
• In MVC terminology,

– the Model corresponds to the state information associated with


the component.

• For example, in the case of a check box, the model contains a


field(variable) that indicates if the box is checked or unchecked.

– The View determines how the component is displayed on the screen, including any
aspects of the view that are affected by the current state of the model. (look)

– The Controller determines how the component reacts to the user. (feel)

• For example, when the user clicks a checkbox, the controller reacts by changing the
model to reflect the user’s choice (checked or unchecked). So view changes.

Downloaded from Ktunotes.in


5.2 - MVC
● By separating a component into a model, a view, and a controller, the specific
implementation of each can be changed without affecting the other two.
● Swing uses a modified version of MVC that combines the view and the controller
into a single logical entity called the UI delegate.
● – So, Swing’s approach is called either the Model-Delegate architecture or the
Separable Model architecture.
● Swing’s Pluggable Look and Feel (PLAF) is made possible by its Model-Delegate
architecture.
● Because the view (look) and controller (feel) are separate from the model, the
look and feel can be changed without affecting how the component is used within
a program.

Downloaded from Ktunotes.in


5.2 - MVC
● To support the Model-Delegate
architecture, most Swing components
contain two objects.

– The first represents the model.

● Models are defined by interfaces

– The second represents the UI


delegate.

● UI delegates are classes that inherit


ComponentUI.

Downloaded from Ktunotes.in


5.2 - Swing controls
Swing controls plays major role in swing
applications, every application will have
some components and their

corresponding event listener.

Swing controls will inherit the properties


from following classes.

– Component

– Container

– JComponent.

Downloaded from Ktunotes.in


5.2 - Class hierarchy

Downloaded from Ktunotes.in


5.2 - Swing controls
Some swing controls are

– Container Control(Parent control)

• It hold other controls(child controls or components)

– JFrame, JPanel

– Child Control –These controls are inside container control

• They can only exist inside container control. They can be components or
containers.

– JTextArea,JLabel, JButton

• When container control is deleted then its child controls are also deleted.

Downloaded from Ktunotes.in


5.2 - Swing Components and Containers
A Swing GUI consists of two key items: components and containers

A container holds a group of components.

– So a container is a special type of component that is designed to hold other


components.

To display a component, it must be held within a container.

So all Swing GUIs will have at least one container.

Because containers are components, a container can also hold other containers.

Downloaded from Ktunotes.in


5.2 - Components
Swing components are derived from the JComponent class.

JComponent provides the functionality that is common to all components.

E.g JComponent supports the pluggable look and feel.

JComponent inherits the AWT classes Container and Component..

– So, a Swing component is built on and compatible with an AWT component.

All of Swing’s components are represented by classes defined within the package
javax.swing.

Downloaded from Ktunotes.in


5.2 - Components
The class names for Swing components are

Downloaded from Ktunotes.in


5.2 - Containers
• Swing defines two types of
containers.

– The first are top-level


containers(heavyweight)

– The second type of containers


supported by Swing are lightweight
containers.

Downloaded from Ktunotes.in


5.2 - Top-level Containers
• The first are top-level containers
– JFrame, JApplet, JWindow, and JDialog.
– These containers do not inherit JComponent
– They inherit the AWT classes Component and Container
– The top-level containers are heavyweight.
– A top-level container must be at the top of a containment
hierarchy
– A top-level container is not contained within any other
container.
– Every containment hierarchy must begin with a top-level
container.
– The one most commonly used for applications is JFrame.
– The one used for applets is JApplet.
Downloaded from Ktunotes.in
5.2 - Lightweight Containers
• The second type of containers supported by Swing are lightweight containers.
– Lightweight containers do inherit JComponent.
• E.g. JPanel is a general-purpose container.
– Lightweight containers are often used to organize and manage groups of related
components because a lightweight container can be contained within another
container.
– We can use lightweight containers such as JPanel to create subgroups of
related controls that are contained within an outer container.

Downloaded from Ktunotes.in


5.2 - Containers

Downloaded from Ktunotes.in


5.2 - The Top-Level Container Panes
• The Top-Level Container Panes
– Each top-level container defines a set of
panes.
– At the top of the hierarchy is an instance of
JRootPane.
• JRootPane is a lightweight container whose
purpose is to manage the other panes.
• It also helps manage the optional menu bar.
• The panes that comprise the root pane are
called
– the glass pane,
– the content pane,
– the layered pane.
Downloaded from Ktunotes.in
5.2 - The Top-Level Container Panes
• Glass pane :
– The glass pane is the top-level pane.
– It sits above and completely covers all other panes.
– By default, it is a transparent instance of JPanel.
• Layered pane :
– The layered pane is an instance of JLayeredPane.
– The layered pane allows components to be given a depth value.
– This value determines which component overlays another.
• Content pane:
– The pane with which your application will interact the most is the content pane
– When we add a component, such as a button, to a top- level container, we will
add it to the content pane.
– By default, the content pane is an opaque instance of JPanel.
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
5.3 - Swing Packages, Event handling in Swing
Swings
● Swing Packages
● Event Handling in Swings.

Swing is a very large subsystem and makes use of many packages.

These are the packages used by Swing that are defined by Java SE 6.

The main package is javax.swing.

– This package must be imported into any program that uses Swing.

– It contains the classes that implement the basic Swing components, such as
push buttons, labels, and check boxes.

Downloaded from Ktunotes.in


5.3 - Swing Packages

Downloaded from Ktunotes.in


5.3 - Swing Application
There are two types of Java programs in which Swing is typically used.

1. Desktop Application. - An application is a standalone java program that can be


directly run on the machine.

2. Applet - Applets are small Java programs that are designed to be included with
the HTML web document.

They require a Java-enabled web browser for execution. At present most of the
browsers do not support applet.

Downloaded from Ktunotes.in


5.4 - Swing Layout Managers
Refer attached PPT in Google Classroom

Downloaded from Ktunotes.in


5.3 - A Simple Swing Application
Q. Write a swing program that uses two Swing components:Jframe and JLabel.

The program uses a JFrame container to hold an instance of a JLabel. The label
displays a short text message

• JFrame is the top-level container that is commonly used for Swing applications.
JLabel is the Swing component that creates a label, which is a component that
displays information.

The label is Swing’s simplest component because it is passive.

● a label does not respond to user input. It just displays output.

Refer attached PPT in Google Classroom

Downloaded from Ktunotes.in


5.5 - Exploring Swing - JFrame, JLabel, JButton,
JTextField

Downloaded from Ktunotes.in


5.5 - Exploring Swing - JFrame, JLabel, JButton,
JTextField
● JFrame class is a type of container which inherits the java. awt. Frame class.
JFrame works like the main window where components like labels, buttons,
text fields are added to create a GUI.
● JLabel is a class of java Swing . JLabel is used to display a short string or an
image icon. JLabel can display text, image or both . JLabel is only a display of
text or image and it cannot get focus . JLabel is inactive to input events such
a mouse focus or keyboard focus.
● The JButton class is used to create a labeled button that has platform
independent implementation. On click, it produces action event.
● JTextField is a lightweight component that allows the editing of a single line of
text
● A JTextArea is a multi-line area that displays plain text. It is intended to be a
lightweight component that provides source compatibility with the java. Awt.
● This is a reading assignment
Downloaded and meant
from for self study
Ktunotes.in
JDBC
Refer attached PPT in Google Classroom

Downloaded from Ktunotes.in


References
● Herbert Schildt, Java: The Complete Reference, 8/e, Tata McGraw Hill, 2011.

● GeeksforGeeks - www.geeksforgeeks.org

● Wikipedia - www.wikipedia.org

● Tutorialspoint - www.tutorialspoint.com

● Java Zone - https://dzone.com

● https://itsmeebin.wordpress.com/

● https://renethajb.wordpress.com/
Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the
respective content creators. Document is compiled exclusively for study purpose and shall not be used for
commercial purpose.
Downloaded from Ktunotes.in
CS205 Object Oriented Programming in
Java
Module 5 - Graphical User Interface and
Database support of Java
(Part 3)
Prepared by
Renetha J.B.
AP
Dept.of CSE,
Lourdes Matha College of Science and Technology

Prepared by Renetha J.B. 1

Downloaded from Ktunotes.in


Topics

Swings
Swing Packages

Event Handling in Swings.

Prepared by Renetha J.B. 2

Downloaded from Ktunotes.in


Swing Packages
• Swing is a very large subsystem and makes use of many
packages.

– These are the packages used by Swing that are defined by


Java SE 6.

• The main package is javax.swing.

– This package must be imported into any program that


uses Swing.

– It contains the classes that implement the basic Swing


components, such as push buttons, labels, and check
boxes. Prepared by Renetha J.B. 3

Downloaded from Ktunotes.in


Swing packages(contd.)
javax.swing javax.swing.border javax.swing.colorchooser

javax.swing.event javax.swing.filechooser javax.swing.plaf

javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi

javax.swing.plaf.synth javax.swing.table javax.swing.text

javax.swing.text.html javax.swing.text.html.par javax.swing.text.rtf


ser

javax.swing.tree javax.swing.undo

Prepared by Renetha J.B. 4

Downloaded from Ktunotes.in


A Simple Swing Application
• There are two types of Java programs in which Swing is
typically used.

1. desktop application.

2. applet

Prepared by Renetha J.B. 5

Downloaded from Ktunotes.in


A Simple Swing Application
• Q. Write a swing program that uses two Swing components:
Jframe and JLabel. The program uses a JFrame container
to hold an instance of a JLabel. The label displays a short text
message

• JFrame is the top-level container that is commonly used for


Swing applications. JLabel is the Swing component that
creates a label, which is a component that displays
information. The label is Swing’s simplest component
because it is passive.

– That is, a label does not respond to user input. It just


displays output.

Prepared by Renetha J.B. 6

Downloaded from Ktunotes.in


import javax.swing.*;
class SwingDemo
{
SwingDemo()
{
// Create a new JFrame container. With title- A Simple Swing
JFrame jfrm = new JFrame("A Simple Swing ");

// Give the frame an initial size. Width=275 height =100


jfrm.setSize(275, 100);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Prepared by Renetha J.B. 7

Downloaded from Ktunotes.in


// Create a text-based label
JLabel jlab = new JLabel(" Swing is powerful GUI");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame. Too compile this program,
jfrm.setVisible(true); javac SwingDemo.java
} To run the program,
java SwingDemo
public static void main(String args[])
{
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
new SwingDemo();
}
}
);
} }
Prepared by Renetha J.B. 8

Downloaded from Ktunotes.in


// A simple Swing application. JLabel jlab = new JLabel(" Swing is
import javax.swing.*; powerful GUI");
// Add the label to the content pane.
class SwingDemo {
jfrm.add(jlab);
SwingDemo() { // Display the frame.
// Create a new JFrame container. jfrm.setVisible(true);
JFrame jfrm = new JFrame("A Simple Swing "); }
// Give the frame an initial size. public static void main(String args[])
{
jfrm.setSize(275, 100); // Create the frame on the event
// Terminate the program when the user closes dispatching thread.
the application. SwingUtilities.invokeLater(new
Runnable() {
jfrm.setDefaultCloseOperation(JFrame.EXI
public void run() {
T_ON_CLOSE);
new SwingDemo();
// Create a text-based label }
});
}
}
Prepared by Renetha J.B. 9

Downloaded from Ktunotes.in


• javax.swing defines classes that implement labels, buttons,
text controls, and menus.
• The constructor is where most of the action of the program
occurs. It begins by creating a JFrame, using this line of code:
JFrame jfrm = new JFrame("A Simple Swing ");
• This creates a container called jfrm that defines a rectangular
window complete with a title bar; close, minimize,
maximize, and restore buttons; and a system menu.
• Thus, it creates a standard, top-level window.
• The title of the window is passed to the constructor
– Here title is A Simple Swing
Prepared by Renetha J.B. 10

Downloaded from Ktunotes.in


• The window is sized using this statement:
jfrm.setSize(275, 100);
• The setSize( ) method (which is inherited by JFrame from the
AWT class Component) sets the dimensions of the window,
which are specified in pixels. Its general form :
void setSize(in t width, int height)

• We want the entire application to terminate when its top-


level window is closed. There are a couple of ways to achieve
this. The easiest way is to call setDefaultCloseOperation( ),
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• After this call executes, closing the window causes the entire
application to terminate.
Prepared by Renetha J.B. 11

Downloaded from Ktunotes.in


• The general form of setDefaultCloseOperation( ) is :
void setDefaultCloseOperation(int what)

– The value passed in what determines what happens when the


window is closed.
• There are several options :
JFrame.EXIT_ON_CLOSE
JFrame.DISPOSE_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE

Prepared by Renetha J.B. 12

Downloaded from Ktunotes.in


• The next line of code creates a Swing JLabel component:

JLabel jlab = new JLabel(" Swing is powerful GUI");

• The next line of code adds the label to the content pane of the
frame:

jfrm.add(jlab);

• Thus, to add a component to a frame, we must add it to the


frame’s content pane. This is accomplished by calling add( )
on the JFrame reference (jfrm in this case). The general
form of add( ) is:

Component add(Component comp)


Prepared by Renetha J.B. 13

Downloaded from Ktunotes.in


• The content pane can be obtained by calling getContentPane( )
on a JFrame instance

Container getContentPane( )

• The last statement in the SwingDemo constructor causes the


window to become visible:

jfrm.setVisible(true);

Prepared by Renetha J.B. 14

Downloaded from Ktunotes.in


• SwingDemo constructor is invoked using the following lines of
code:
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
new SwingDemo();
}
}
);
• This sequence causes a SwingDemo object to be created on the
event dispatching thread rather than on the main thread of the
application.
• Swing programs are event-driven.
Prepared by Renetha J.B. 15

Downloaded from Ktunotes.in


• To enable the GUI code to be created on the event
dispatching thread, we must use one of two methods that are
defined by the SwingUtilities class.
• These methods are
– invokeLater( )
– invokeAndWait( ).
static void invokeLater(Runnable obj)
static void invokeAndWait(Runnable obj)
throws InterruptedException, InvocationTargetException

• The difference between the two methods is that


– invokeLater() returns immediately,
– but invokeAndWait( ) waits until obj.run( ) returns
Prepared by Renetha J.B. 16

Downloaded from Ktunotes.in


Event Handling in Swings
• Delegation event model is the event handling mechanism
used by Swing.

• Swing uses the same events as does the AWT, and these events
are packaged in java.awt.event.

• Events specific to Swing are stored in javax.swing.event

Prepared by Renetha J.B. 17

Downloaded from Ktunotes.in


Swing-Event handling E.g.
• Q. Write a program in swing to create a frame with title “An
Event Example ”.
– Give FlowLayout to frame and set a width =220 and height=90
– Frame has two buttons Ok and Cancel.
– Frame has a label that display the message “Push a button”.
– When we click the OK button it prints the message “OK
pressed” in the label.
– When we click the Cancel button it prints the message “Cancel
pressed” in the label

Prepared by Renetha J.B. 18

Downloaded from Ktunotes.in


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemo extends JFrame implements ActionListener
{ JLabel jlab;
EventDemo()
{ // Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
// Specify FlowLayout for the layout manager.
jfrm.setLayout(new FlowLayout());
// Give the frame an initial size.
jfrm.setSize(220, 90);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.
JButton jbtnOk = new JButton("OK");
JButton jbtnCancel = new JButton("Cancel");
Prepared by Renetha J.B. 19

Downloaded from Ktunotes.in


// Add action listener for Ok button.
jbtnOk.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jlab.setText("OK pressed.");
}
}
);
// Add action listener for Cancel button.
jbtnCancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
jlab.setText("Cancel pressed.");
}
}
);

Prepared by Renetha J.B. 20

Downloaded from Ktunotes.in


// Add the buttons to the content pane.
jfrm.add(jbtnOk);
jfrm.add(jbtnCancel);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
jfrm.add(jlab);
// Display the frame.
jfrm.setVisible(true);
}

Prepared by Renetha J.B. 21

Downloaded from Ktunotes.in


public static void main(String args[])
{
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new EventDemo();
}
}
);
}
}

Prepared by Renetha J.B. 22

Downloaded from Ktunotes.in


• The java.awt package is needed because
– it contains the FlowLayout class, which supports the
standard flow layout manager used to lay out components
in a frame
– It defines the ActionListener interface and the ActionEvent
class.
• The EventDemo constructor begins by creating a JFrame
called jfrm with title -An Event Example
JFrame jfrm = new JFrame("An Event Example");
• It then sets thelayout manager for the content pane of jfrm to
FlowLayout.
jfrm.setLayout(new FlowLayout());
• By default, the content pane uses BorderLayout as its layout
manager.
Prepared by Renetha J.B. 23

Downloaded from Ktunotes.in


• After setting the size and default close operation,
EventDemo() creates two push buttons, as shown here:
JButton jbtnOk = new JButton(“Ok");
JButton jbtnCancel = new JButton(”Cancel");
– The first button will contain the text “Ok” and the second will
contain the text “Cancel”.

• When a push button is pressed, it generates an ActionEvent.


• Thus, JButton provides the addActionListener( ) method,
which is used to add an action listener so that button will
respond to events. (JButton also provides
removeActionListener( ) to remove a listener)

Prepared by Renetha J.B. 24

Downloaded from Ktunotes.in


• event listeners for the button’s action events are added by the code shown belo:
• // Add action listener for Ok button.
jbtnOK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{ jlab.setText(“OKwas pressed.");
}
});
This can also be written as:
jbtnOK.addActionListener(this);
…………………………………
}
public void actionPerformed(ActionEvent ae)
{ String s = ae.getActionCommand(); //to get the name written in button
if(s.equalsIgnoreCase("ok")) //to have case insensitive comparison
jlab.setText("OK pressed.");
} Prepared by Renetha J.B. 25

Downloaded from Ktunotes.in


Simple Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class EventDemoSwing extends JFrame implements ActionListener
{ JLabel jlab;
EventDemoSwing()
{ JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtnOk = new JButton("OK");
JButton jbtnCancel = new JButton("Cancel");
jbtnOk.setToolTipText("click");
jbtnOk.addActionListener(this);
jbtnCancel.addActionListener(this);
jfrm.add(jbtnOk);
jfrm.add(jbtnCancel);
jlab = new JLabel("Press a button.");
jfrm.add(jlab);
jfrm.setVisible(true);
} Prepared by Renetha J.B. 26

Downloaded from Ktunotes.in


public void actionPerformed(ActionEvent ae)
{ //store the name written in button that is clicked ,in variable s
String s = ae.getActionCommand();
if(s.equalsIgnoreCase("ok"))
jlab.setText("OK pressed.");
else if(s.equalsIgnoreCase("cancel"))
jlab.setText("Cancel pressed.");
}
public static void main(String args[])
{ SwingUtilities.invokeLater(new Runnable()
{ public void run()
{
new EventDemoSwing();
}
}
);
}
Prepared by Renetha J.B. 27
}
Downloaded from Ktunotes.in
Create a Swing Applet
• A Swing applet extends Japplet.
– JApplet is derived from Applet.
• Swing applets use the same four lifecycle methods as
Applet
• init( ),
• start( ), stop( ), and destroy( ).
• Swing applet will not normally override the paint( )
method

Prepared by Renetha J.B. 28

Downloaded from Ktunotes.in


• Write a program using SWING APPLET
– It should have two buttons Ok and Cancel.
– Label to display message “Push a button”.
– When we click the OK button it prints the message “OK
pressed” in the label.
– When we click the Cancel button it prints the message “Cancel
pressed” in the label

Prepared by Renetha J.B. 29

Downloaded from Ktunotes.in


// A simple Swing-based applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/*
This HTML can be used to launch the applet:
<object code="MySwingApplet" width=220 height=90>
</object>
*/
public class MySwingApplet extends JApplet implements ActionListener
{
JButton jbtnOk;
JButton jbtnCancel;
JLabel jlab;

Prepared by Renetha J.B. 30

Downloaded from Ktunotes.in


// Initialize the applet.
public void init() {
try { SwingUtilities.invokeAndWait(new Runnable ()
{
public void run() {
makeGUI(); // initialize the GUI
}
});
} catch(Exception exc)
{
System.out.println("Can't create because of "+ exc); }
}

Prepared by Renetha J.B. 31

Downloaded from Ktunotes.in


private void makeGUI()
{ // Set the applet to use flow layout.
setLayout(new FlowLayout());
// Make two buttons.
jbtnOk = new JButton("Ok");
jbtnCancel = new JButton("Cancel");
// Add action listener for ok.
jbtnOk.addActionListener(this);
// Add action listener for Cancel.
jbtnCancel.addActionListener(this);
// Add the buttons to the content pane.
add(jbtnOk);
add(jbtnCancel);
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
add(jlab);
} Prepared by Renetha J.B. 32

Downloaded from Ktunotes.in


public void actionPerformed(ActionEvent ae)
{
String s = ae.getActionCommand();
if(s.equalsIgnoreCase("Ok"))
jlab.setText("Ok was pressed.");
else if(s.equalsIgnoreCase("Cancel"))
jlab.setText("Cancel was pressed.");
}
} COMPILE
javac MySwingApplet.java

RUN
appletviewer MySwingApplet.java

Prepared by Renetha J.B. 33

Downloaded from Ktunotes.in


Reference
• Herbert Schildt, Java: The Complete Reference, 8/e,
Tata McGraw Hill, 2011.

Prepared by Renetha J.B. 34

Downloaded from Ktunotes.in


CS205 Object Oriented Programming in
Java
Module 5 - Graphical User Interface and
Database support of Java
(Part 4)
Prepared by
Renetha J.B.
AP
Dept.of CSE,
Lourdes Matha College of Science and Technology

1
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


Topics

Swings
Swing Layout Managers

Prepared by Renetha J.B. 2

Downloaded from Ktunotes.in


Swing Layout Managers
• A layout manager automatically arranges our controls
within a window by using some type of algorithm.
• Each Container object has a layout manager associated with it.
• A layout manager is an instance of any class that implements
the LayoutManager interface.
• The layout manager is set by the setLayout( ) method.
– If no call to setLayout( ) is made, then the default layout
manager is used.
• The setLayout( ) method has the following general form:

void setLayout(LayoutManager layoutObj)

Prepared by Renetha J.B. 3

Downloaded from Ktunotes.in


Swing Layout Managers(contd.)
• The layout manager is notified each time we add a component
to a container.

• Each layout manager keeps track of a list of components that


are stored by their names.

• Whenever the container needs to be resized, the layout


manager is consulted via its minimumLayoutSize( ) and
preferredLayoutSize( ) methods.
– Each component that is being managed by a layout manager
contains the getPreferredSize( ) and getMinimumSize( )
methods.
Prepared by Renetha J.B. 4

Downloaded from Ktunotes.in


• Java has several predefined LayoutManager classes,
– FlowLayout

– BorderLayout

– GridLayout

– CardLayout

– GridBagLayout

Prepared by Renetha J.B. 5

Downloaded from Ktunotes.in


FlowLayout
• The direction of the layout is governed by the container’s
component orientation property, which, by default, is left to
right, top to bottom.
• In low Layout
– components are laid out line-by-line beginning at the upper-
left corner.
– When a line is filled, layout advances to the next line.
– A small space is left between each component, above and below,
as well as left and right.
• The constructors for FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert) Prepared by Renetha J.B. 6

Downloaded from Ktunotes.in


FlowLayout(contd.)
• FlowLayout( ) creates the default layout, which centers
components and leaves five pixels of space between each
component.
• FlowLayout(int how) lets us specify how each line is aligned.
– Valid values for how are as follows:
• FlowLayout.LEFT
• FlowLayout.CENTER
• FlowLayout.RIGHT
• FlowLayout.LEADING
• FlowLayout.TRAILING
– These values specify left, center, right, leading edge, and
trailing edge alignment, respectively.
• FlowLayout(int how, int horz, int vert) allows us to specify the
horizontal and vertical space left between components in
horz and vert, respectively.
Prepared by Renetha J.B. 7

Downloaded from Ktunotes.in


import java.awt.*; import java.awt.event.*;
import javax.swing.*;
class EventDemoSwing extends JFrame implements
ActionListener{
JLabel jlab;
public void actionPerformed(ActionEvent ae)
JFrame jfrm;
JButton jbtnOk; {
JButton jbtnCancel; String s = ae.getActionCommand();
EventDemoSwing() if(s.equalsIgnoreCase("ok"))
{ jlab.setText("OK pressed.");
jfrm = new JFrame("An Event Eg"); else if(s.equalsIgnoreCase("cancel"))
jfrm.setLayout(new FlowLayout()); jlab.setText("Cancel pressed.");
jfrm.setSize(220, 90); }
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnOk = new JButton("OK");
JButton jbtnCancel = new JButton("Cancel");
jbtnOk.setToolTipText("click"); public static void main(String args[])
jbtnOk.addActionListener(this); {SwingUtilities.invokeLater(new Runnable()
jbtnCancel.addActionListener(this); {
jfrm.add(jbtnOk); public void run()
jfrm.add(jbtnCancel); { new EventDemoSwing();
jlab = new JLabel("Press a button."); }
jfrm.add(jlab); } );
Prepared by Renetha J.B.

jfrm.setVisible(true); } 8
} }

Downloaded from Ktunotes.in


FlowLayout(contd.)

If in code we modify the layout as


jfrm.setLayout(new FlowLayout(FlowLayout.LEFT));

Prepared by Renetha J.B.


9

Downloaded from Ktunotes.in


BorderLayout
• By default, the content pane associated with a JFrame uses
border layout.
• The BorderLayout class implements a common layout style
for top-level windows.
• It has four narrow, fixed-width components at the edges and
one large area in the center.
• The four sides are referred to as
– North,
– South
– East
– West.
• The middle area is called
– Center
Prepared by Renetha J.B. 10

Downloaded from Ktunotes.in


BorderLayout(contd.)
• The constructors defined by BorderLayout:

BorderLayout( )

• BorderLayout( ) creates a default border layout.

• BorderLayout(int horz, int vert) specify the horizontal and


vertical space left between components in horz and vert,
respectively

Prepared by Renetha J.B. 11

Downloaded from Ktunotes.in


BorderLayout(contd.)
• BorderLayout defines the following constants
– BorderLayout.CENTER
– BorderLayout.SOUTH
– BorderLayout.EAST
– BorderLayout.WEST
– BorderLayout.NORTH
• When adding components, you will use these constants with
the following form ofadd( ), which is defined by Container:

void add(Component compObj, Object region)

– Here, compObj is the component to be added, and region


specifies where the component will be added.
Prepared by Renetha J.B. 12

Downloaded from Ktunotes.in


import java.awt.*; import java.awt.event.*;
import javax.swing.*;
class EventDemoSwing extends JFrame implements
ActionListener{
JLabel jlab;
public void actionPerformed(ActionEvent ae)
JFrame jfrm;
JButton jbtnOk; {
JButton jbtnCancel; String s = ae.getActionCommand();
EventDemoSwing() if(s.equalsIgnoreCase("ok"))
{ jlab.setText("OK pressed.");
jfrm = new JFrame("An Event Eg"); else if(s.equalsIgnoreCase("cancel"))
jfrm.setLayout(new BorderLayout ()); jlab.setText("Cancel pressed.");
jfrm.setSize(220, 90); }
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnOk = new JButton("OK");
JButton jbtnCancel = new JButton("Cancel");
jbtnOk.setToolTipText("click"); public static void main(String args[])
jbtnOk.addActionListener(this); {SwingUtilities.invokeLater(new Runnable()
jbtnCancel.addActionListener(this); {
jfrm.add(jbtnOk,BorderLayout.EAST); public void run()
jfrm.add(jbtnCancel, BorderLayout.WEST); { new EventDemoSwing();
jlab = new JLabel("Press a button."); }
jfrm.add(jlab BorderLayout.NORTH); } );
jfrm.setVisible(true); } 13
} } Prepared by Renetha J.B.

Downloaded from Ktunotes.in


BorderLayout(contd.)

Prepared by Renetha J.B. 14

Downloaded from Ktunotes.in


Using Insets
• Sometimes we may want to leave a small amount of space
between the container that holds the components and the
window that contains it.
– To do this, override the getInsets( ) method that is defined by
Container.
– getInsets( ) method returns an Insets object that contains
the top, bottom, left, and right inset to be used when the
container is displayed.
– These values are used by the layout manager to inset the
components when it lays out the window
• The constructor for Insets is shown here:
Insets(int top, int left, int bottom, int right)
– The values passed in top, left, bottom, and right specify the
amount of space between the container and its enclosing window
Prepared by Renetha J.B. 15

Downloaded from Ktunotes.in


Using Insets(contd.)
• The getInsets( ) method has this general form:

Insets getInsets( )
– When overriding this method, we must return a new Insets
object that contains the inset spacing you desire.

Prepared by Renetha J.B. 16

Downloaded from Ktunotes.in


GridLayout
• GridLayout lays out components in a two-dimensional grid.
– We can define the number of rows and columns.
• The constructors supported by GridLayout are
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayolayoutut(int numRows, int numColumns, int horz, int vert)
– GridLayout( ) creates a single-column grid
– GridLayout(int numRows, int numColumns) creates a grid layout
with the specified number of rows and columns.
– GridLayolayoutut(int numRows, int numColumns, int horz, int vert)
allows us to specify the horizontal and vertical space left between
components in horz and vert, respectively. Either numRows or
numColumns can be zero. Specifying numRows as zero allows for
unlimited-length columns.
Prepared by Renetha J.B. 17

Downloaded from Ktunotes.in


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class GridDemo extends JFrame implements ActionListener
{ JLabel jlab;
public void actionPerformed(ActionEvent ae)
JFrame jfrm;
GridDemo() { String s = ae.getActionCommand();
{ jfrm = new JFrame("An Event Eg"); if(s.equalsIgnoreCase("one"))
jfrm.setLayout(new GridLayout (2,2)); jlab.setText("One pressed.");
jfrm.setSize(220, 90); else if(s.equalsIgnoreCase("two"))
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jlab.setText("Two pressed.");
JButton jbtnOne = new JButton("One"); else if(s.equalsIgnoreCase("three"))
JButton jbtnTwo= new JButton("Two"); jlab.setText("Three pressed.");
JButton jbtnThree = new JButton("Three");
else if(s.equalsIgnoreCase("four"))
JButton jbtnFour = new JButton("Four");
jlab.setText("Four pressed.");
jbtnOne.addActionListener(this);
jbtnTwo.addActionListener(this); }
jbtnThree.addActionListener(this); public static void main(String args[])
jbtnFour.addActionListener(this); {SwingUtilities.invokeLater(new Runnable()
jfrm.add(jbtnOne); { public void run()
jfrm.add(jbtnTwo); { new GridDemo(); } }
jfrm.add(jbtnThree); );
jfrm.add(jbtnFour); }
jfrm.setVisible(true); 18
} Prepared by Renetha J.B.
}
Downloaded from Ktunotes.in
jfrm.setLayout(new GridLayout (2,2));
• This set 2 rows and 2 columns
• Components are filled in order from first row first column
(0,0) (0,1)
(1,0) (1,1)

Prepared by Renetha J.B. 19

Downloaded from Ktunotes.in


CardLayout
• The CardLayout class is unique among the other layout
managers in that it stores several different layouts.
• Each layout can be thought of as being on a separate index
card in a deck that can be shuffled so that any card is on top
at a given time
• This can be useful for user interfaces with optional
components that can be dynamically enabled and disabled
upon user input.
• CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
– CardLayout( ) creates a default card layout.
– CardLayout(int horz, int vert) allows to specify the horizontal
and vertical space left between components in horz and vert,
respectively.
Prepared by Renetha J.B. 20

Downloaded from Ktunotes.in


CardLayout(contd.)
• The cards are typically held in an object of type Panel.

• This panel must have CardLayout selected as its layout


manager.

• The cards that form the deck are also typically objects of type
Panel

Prepared by Renetha J.B. 21

Downloaded from Ktunotes.in


CardLayout(contd.)
• We must create
– a panel that contains the deck and
– a panel for each card in the deck.
• Next, we add components that form each card to the
appropriate panel.
• We then add these panels to the panel for which CardLayout
is the layout manager.
• Finally, we add this panel to the window.

• Once these steps are complete, we must provide some way for
the user to select between cards.
– One common approach is to include one push button for each
card in the deck.

Prepared by Renetha J.B. 22

Downloaded from Ktunotes.in


CardLayout(contd.)
• Use add( ) when adding cards to a panel:
void add(Component panelObj, Object name)
– Here, name is a string that specifies the name of the card whose
panel is specified by panelObj.
• After we have created a deck, our program activates a card by
calling one of the following methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
– Here, deck is a reference to the container (usually a panel) that holds
the cards, and cardName is the name of a card.
– Calling first( ) causes the first card in the deck to be shown. To
show the last card, call last( ). To show the next card, call next( ).
To show the previous card, call previous( ). Both next( ) and
previous( ) automatically cycle back to the top or bottom of the
deck, respectively. The show( ) method displays the card whose
name is passed in cardName. Prepared by Renetha J.B. 23

Downloaded from Ktunotes.in


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo extends JFrame implements
ActionListener
{
CardLayout card; public void actionPerformed(ActionEvent e)
JButton b1,b2,b3; {
Container c; card.next(c);
CardLayoutDemo() }
{
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
public static void main(String[] args)
b1=new JButton("Apple");
b2=new JButton("Boy"); {
b3=new JButton("Cat"); CardLayoutDemo cl=new CardLayoutDemo();
b1.addActionListener(this); cl.setSize(400,400);
b2.addActionListener(this); cl.setVisible(true);
b3.addActionListener(this); cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
c.add(b1);c.add(b2);c.add(b3); }
24
Prepared by Renetha J.B.
}
Downloaded from Ktunotes.in
• When we click the button
it changes to next button
like cards
25
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


GridBagLayout
• We can specify the relative placement of components by
specifying their positions within cells inside a grid using
GridBagLayout.
• The key to the grid bag is that each component can be a
different size, and each row in the grid can have a different
number of columns.
– This is why the layout is called a grid bag.
• It’s a collection of small grids joined together.
• The location and size of each component in a grid bag are
determined by a set of constraints linked to it.
• The constraints are contained in an object of type
GridBagConstraints.
– Constraints include the height and width of a cell, and the
placement of a component, its alignment, and its anchor point
within the cell.
Prepared by Renetha J.B. 26

Downloaded from Ktunotes.in


GridBagLayout(contd.)
• The general procedure for using a grid bag is to
– first create a new GridBagLayout object and to make it the
current layout manager.
– Then, set the constraints that apply to each component that will
be added to the grid bag.
– Finally, add the components to the layout manager.
• GridBagLayout defines only one constructor
GridBagLayout( )
• GridBagLayout defines several methods, of which many are
protected and not for general use.
• One method is setConstraints( )
void setConstraints(Component comp, GridBagConstraints cons)

Prepared by Renetha J.B. 27

Downloaded from Ktunotes.in


GridBagLayout(contd.)
GridBagConstraints defines several fields that to govern the size,
placement, and spacing of a component.

Prepared by Renetha J.B. 28

Downloaded from Ktunotes.in


GridBagLayout(contd.)
• GridBagConstraints also defines several static fields that
contain standard constraint values, such as
– GridBagConstraints.CENTER
– GridBagConstraints.VERTICAL
• When a component is smaller than its cell, you can use the
anchor field to specify where within the cell the component’s
top-left corner will be locate

Prepared by Renetha J.B. 29

Downloaded from Ktunotes.in


GridBagLayout(contd.)
• The second type of values that can be given to anchor is
relative, which means the values are relative to the container’s
orientation,

Prepared by Renetha J.B. 30

Downloaded from Ktunotes.in


import java.awt.*; import java.awt.event.*; import javax.swing.*;
public GridLayoutDemo() {
jfrm = new JFrame("An Event Eg");
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
jfrm.setLayout(gbag);
jfrm.setSize(520, 500);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnOk = new JButton("OK");
jbtnCancel = new JButton("Cancel");
jbtnOk.setToolTipText("click");
jbtnOk.addActionListener(this);
jbtnCancel.addActionListener(this);
//Define the grid bag. // Use default row weight of 0 for first row.
gbc.weightx = 1.0; // use a column weight of 1
gbc.ipadx = 200; // pad by 200 units
gbc.insets = new Insets(4, 4, 10, 10); // inset slightly from top left
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(jbtnOk, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER; Prepared by Renetha J.B.
gbag.setConstraints(jbtnCancel, gbc); 31

Downloaded from Ktunotes.in


jlab = new JLabel("Press a button.");

jfrm.add(jbtnOk);
jfrm.add(jbtnCancel);
jfrm.add(jlab);

jfrm.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String s = ae.getActionCommand();
if(s.equalsIgnoreCase("ok"))
jlab.setText("OK pressed.");
else if(s.equalsIgnoreCase("cancel"))
jlab.setText("Cancel pressed.");
}

Prepared by Renetha J.B. 32

Downloaded from Ktunotes.in


Prepared by Renetha J.B. 33

Downloaded from Ktunotes.in


Reference
• Herbert Schildt, Java: The Complete Reference, 8/e,
Tata McGraw Hill, 2011.

Prepared by Renetha J.B. 34

Downloaded from Ktunotes.in


CS205 Object Oriented Programming in
Java
Module 5 - Graphical User Interface and
Database support of Java
(Part 5)
Prepared by
Renetha J.B.
AP
Dept.of CSE,
Lourdes Matha College of Science and Technology

1
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


Topics

Swings
Exploring Swings

JFrame

Jlabel

The Swing Buttons

JTextField

Prepared by Renetha J.B. 2

Downloaded from Ktunotes.in


• Some of the swing components are:
– JButton
– JCheckBox These components are all lightweight.
They are all derived from
– JComboBox JComponent.
– JLabel
– JList
– JRadioButton
– JScrollPane
– JTabbedPane
– JTable
– JTextField
– JToggleButton
– JTree
Prepared by Renetha J.B. 3

Downloaded from Ktunotes.in


JFrame
• Every containment hierarchy must begin with a top-level
container.

• JFrame is a top level container that is commonly used for


Swing applications.

• JFrame do not inherit JComponent.

• JFrame inherit the AWT classes Component and Container.

• The top-level containers are heavyweight.

Prepared by Renetha J.B. 4

Downloaded from Ktunotes.in


JFrame(contd.)
JFrame jfrm = new JFrame(“Swing Example);

• This creates a container called jfrm that

– defines a rectangular window complete with a title bar; close,


minimize, maximize, and restore buttons; and a system
menu.

– Thus, it creates a standard, top-level window.

– The title of the window is passed to the constructor.

• Here it is Swing Example

Prepared by Renetha J.B. 5

Downloaded from Ktunotes.in


JFrame(contd.)
• The setSize( ) method (which is inherited by JFrame from the
AWT class Component) sets the dimensions of the window,
which are specified in pixels.

• Its general form is :

void setSize(int width, int height)

E.g. jfrm.setSize(275, 100);

Prepared by Renetha J.B. 6

Downloaded from Ktunotes.in


JFrame(contd.)
• If we want the entire application to terminate when its top-
level window is closed the easiest way is to call
setDefaultCloseOperation( )
E.g.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
• After this call executes, closing the window causes the entire
application to terminate.
• The general form of setDefaultCloseOperation( ) is :
void setDefaultCloseOperation(int what)
– what can be
• JFrame.EXIT_ON_CLOSE
• JFrame.DISPOSE_ON_CLOSE
• JFrame.HIDE_ON_CLOSE
• JFrame.DO_NOTHING_ON_CLOSE
Prepared by Renetha J.B. 7

Downloaded from Ktunotes.in


JFrame(contd.)
• The content pane can be obtained by calling getContentPane( )
on a JFrame instance.
• The getContentPane( ) method is :
Container getContentPane( )
• The setVisible( ) method is inherited from the AWT Component
class.
– If its argument is true, the window will be displayed. Otherwise, it
will be hidden.
• By default, a JFrame is invisible, so setVisible(true) must be
called to show it.
– E.g.
jfrm.setVisible(true);

Prepared by Renetha J.B. 8

Downloaded from Ktunotes.in


JLabel
• JLabel is Swing’s easiest-to-use component.
• It creates a label.
• JLabel can be used to display text and/or an icon.
• It is a passive component because it does not respond to user
input.
• JLabel defines several constructors:
JLabel(Icon icon)

JLabel(String str)

JLabel(String str, Icon icon, int align)


– The align argument specifies the horizontal alignment of the text and/or
icon within the dimensions of the label.
• It must be one of the following values: LEFT, RIGHT, CENTER,
LEADING, or TRAILING
Prepared by Renetha J.B. 9

Downloaded from Ktunotes.in


JLabel(contd.)
• The easiest way to obtain an icon is to use the ImageIcon class.
• ImageIcon implements Icon and encapsulates an image.
• The following ImageIcon constructor obtains the image in the
file named filename. the Icon parameter of JLabel’s
constructor
ImageIcon(String filename)
• The icon and text associated with the label can be obtained by
the following methods:
Icon getIcon( )
String getText( )
• The icon and text associated with a label can be set by these
methods:
void setIcon(Icon icon)
void setText(String str)
Prepared by Renetha J.B. 10

Downloaded from Ktunotes.in


The Swing Buttons
• Swing defines four types of buttons:
JButton

JToggleButton

JCheckBox

JRadioButton

• All are subclasses of the AbstractButton class (which extends


JComponent)

Prepared by Renetha J.B. 11

Downloaded from Ktunotes.in


The Swing Buttons(contd.)
• AbstractButton contains many methods that allow you to
control the behavior of buttons.
• E.g. We can define different icons that are displayed for the
button when it is disabled, pressed, or selected. Another icon
can be used as a rollover icon, which is displayed when the
mouse is positioned over a button.
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
– Here, di, pi, si, and ri are the icons for specific purpose
Prepared by Renetha J.B. 12

Downloaded from Ktunotes.in


The Swing Buttons (contd.)
• We can get the text associated with a button using:
String getText( )
• We can modify the text associated with a button using:
void setText(String str)

• The model used by all buttons is defined by the


ButtonModel interface.

Prepared by Renetha J.B. 13

Downloaded from Ktunotes.in


JButton
• The JButton class provides the functionality of a push
button.

• JButton allows an icon, a string, or both to be associated


with the push button.

• Three of its constructors are shown here:

JButton(Icon icon)

JButton(String str)

JButton(String str, Icon icon)

• When the button is pressed, an ActionEvent is generated.


Prepared by Renetha J.B. 14

Downloaded from Ktunotes.in


JButton(contd.)
• Using the ActionEvent object passed to the
actionPerformed( ) method of the registered ActionListener,
we can obtain the action command string associated with the
button.
• We can set the action command by calling
setActionCommand( ) on the button.
• We can obtain the action command by calling
getActionCommand( )
String getActionCommand( )
• The action command helps to identify the button.
– Thus, when using two or more buttons within the same
application, the action command gives you an easy way to
determine which button was pressed.

Prepared by Renetha J.B. 15

Downloaded from Ktunotes.in


import javax.swing.*;
import java.awt.*;
import java.awt.event.*; ImageIcon imgok= new
ImageIcon("C:\\RJB\\image1.jpg");
class SwingButton extends JFrame
jbok = new JButton(imgok);
implements ActionListener
jbok.setActionCommand("OK");
{ JFrame jfrm;
jfrm.add(jbok);
JButton jbok , jbcancel; ImageIcon imgcancel= new
JLabel jlab; ImageIcon("C:\\RJB\\image2.jpg");
SwingButton() jbcancel = new JButton(imgcancel);
{ jbcancel.setActionCommand("Cancel");
jfrm = new JFrame("Simple Swing "); jbok.addActionListener(this);
jfrm.setSize(500, 400); jbcancel.addActionListener(this);
jfrm.add(jbcancel);
jfrm.setLayout(new FlowLayout());
jlab = new JLabel(“Waiting button press ");
jfrm.setDefaultCloseOperation(JFram
jfrm.add(jlab);
e.EXIT_ON_CLOSE);
jfrm.setVisible(true);
}
16
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


public void actionPerformed(ActionEvent ae)
{
jlab.setText("You selected " + ae.getActionCommand());
}
public static void main(String args[])
{ SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SwingButton ();
}
}
);
}
}

17
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


JToggleButton
• A toggle button looks just like a push button,
• It acts differently from push button because it has two
states:
– Pushed
– Released
• When we press a toggle button, it stays pressed.
– It does not pop back up as a regular push button.
• When we press the toggle button a second time, it
releases (pops up).
• Each time a toggle button is pushed, it toggles between its
two states
• Toggle buttons are objects of the JToggleButton class.
Prepared by Renetha J.B. 18

Downloaded from Ktunotes.in


JToggleButton(contd.)
• JToggleButton implements AbstractButton.
• JToggleButton is a superclass for JCheckBox and
JRadioButton
• JToggleButton defines several constructors.
JToggleButton(String str)
This creates a toggle button that contains the text passed in str.
• By default, the button is in the off position.
• JToggleButton uses a model defined by a nested class called
JToggleButton .ToggleButtonModel.
• JToggleButton generates an action event each time it is
pressed.
• When a JToggleButton is pressed in, it is selected.
• When it is popped out, it is deselected.
Prepared by Renetha J.B. 19

Downloaded from Ktunotes.in


JToggleButton(contd.)
• To handle item events, we must implement the ItemListener
interface.
• Each time an item event is generated, it is passed to the
itemStateChanged( ) method defined by ItemListener.
• Inside itemStateChanged( ), the getItem( ) method can be
called on the ItemEvent object to obtain a reference to the
JToggleButton instance that generated the event.
Object getItem( )
• The easiest way to determine a toggle button’s state is by
calling the isSelected( ) method.
boolean isSelected( )
– It returns true if the button is selected and false otherwise.

Prepared by Renetha J.B. 20

Downloaded from Ktunotes.in


import javax.swing.*;
import java.awt.*;
import java.awt.event.*; jtbn=new JToggleButton("On/Off");
jtbn.addItemListener(this);
class SwingToggleButton extends
JFrame implements ItemListener jfrm.add(jtbn);
jlab = new JLabel("Button is OFF");
{ JFrame jfrm;
jfrm.add(jlab);
JToggleButton jtbn;
jfrm.setVisible(true);
JLabel jlab;
}
SwingToggleButton() public void itemStateChanged(ItemEvent ie)
{ {
jfrm = new JFrame("Simple Swing "); if(jtbn.isSelected())
jfrm.setSize(500, 400); jlab.setText("Button is on.");
jfrm.setLayout(new FlowLayout()); else
jfrm.setDefaultCloseOperation(JFrame jlab.setText("Button is off.");
.EXIT_ON_CLOSE); }

21
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


public static void main(String args[])
{ SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SwingToggleButton ();
}
}
);
}
}

22
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


JCheckBox
• JCheckBox class provides the functionality of a check box.
• Its immediate superclass is JToggleButton,
• JCheckBox defines several constructors.
JCheckBox(String str)
• When the user selects or deselects a check box, an ItemEvent
is generated.
• Inside the itemStateChanged( ) method, getItem( ) is called
on ItemEvent object to obtain a reference to the JCheckBox
object that generated the event
• To determine the selected state of a check box is to call
isSelected( ) on the JCheckBox instance.

Prepared by Renetha J.B. 23

Downloaded from Ktunotes.in


import javax.swing.*;
import java.awt.*;
import java.awt.event.*; JCheckBox cb = new JCheckBox("C");
cb.addItemListener(this);
class SwingJCheckBox extends JFrame
implements ItemListener jfrm.add(cb);
cb = new JCheckBox("Java");
{ JFrame jfrm;
cb.addItemListener(this);
JCheckBox cb;
jfrm.add(cb);
JLabel jlab;
cb = new JCheckBox("Python");
SwingJCheckBox() cb.addItemListener(this);
{ jfrm.add(cb);
jfrm = new JFrame("Simple Swing ");
jfrm.setSize(500, 400); jlab = new JLabel("Select language");
jfrm.setLayout(new FlowLayout()); jfrm.setVisible(true);
}
jfrm.setDefaultCloseOperation(JFrame
.EXIT_ON_CLOSE);

24
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


public void itemStateChanged(ItemEvent ie)
{ JCheckBox cb = (JCheckBox)ie.getItem();
if(cb.isSelected())
jlab.setText(cb.getText() + " is selected now");
else
jlab.setText(cb.getText() + " is cleared now");
}
public static void main(String args[])
{ SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SwingJCheckbox();
}
});
}}

25
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


26
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


JRadioButton
• Radio buttons are a group of mutually exclusive buttons, in
which only one button can be selected at any one time.
• They are supported by the JRadioButton class, which extends
JToggleButton.
• JRadioButton provides several constructors
JRadioButton(String str)
• Abutton group is created by the ButtonGroup class.
• Its default constructor is invoked for this purpose.
• Elements are then added to the button group via the following
method:
void add(AbstractButton ab)
– Here, ab is a reference to the button to be added to the group.
• A JRadioButton generates action events, item events, and
change Prepared by Renetha J.B. 27

Downloaded from Ktunotes.in


JRadioButton(contd.)
• We will normally implement the ActionListener interface
with method actionPerformed( ).
– Inside this method we can check its action command by
calling getActionCommand( ).
• By default, the action command is the same as the
button label, but we can set the action command to
something else by calling setActionCommand( ) on
the radio button.
• We can call getSource( ) on the ActionEvent object and
check that reference against the buttons.
• We can simply check each radio button to find out which one
is currently selected by calling isSelected( ) on each button.

Prepared by Renetha J.B. 28

Downloaded from Ktunotes.in


import javax.swing.*;
import java.awt.*;
import java.awt.event.*; JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
class SwingJRadioButton extends
JFrame implements ActionListener jfrm.add(b1);
JRadioButton b2 = new JRadioButton("B");
{ JFrame jfrm;
b2.addActionListener(this);
JLabel jlab;
jfrm.add(b2);
SwingJRadioButton()
JRadioButton b3 = new JRadioButton("C");
{ b3.addActionListener(this);
jfrm = new JFrame("Simple Swing "); jfrm.add(b3);
jfrm.setSize(220, 100); ButtonGroup bg = new ButtonGroup();
jfrm.setLayout(new FlowLayout()); bg.add(b1);
jfrm.setDefaultCloseOperation(JFrame bg.add(b2);
.EXIT_ON_CLOSE); bg.add(b3);
jlab = new JLabel("Select language");
jfrm.setVisible(true);
}
29
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


public void actionPerformed(ActionEvent ae)
{
jlab.setText("You selected " + ae.getActionCommand());
}
public static void main(String args[])
{ SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SwingJRadioButton ();
}
});
}}

30
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


JTextField.
• JTextField is the simplest Swing text component.
• JTextField allows you to edit one line of text.
– It is derived from JTextComponent, which provides the
basic functionality common to Swing text components.
• Three of JTextField’s constructors are :
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
– Here, str is the string to be initially presented, and cols is the
number of columns in the text field. If no string is specified, the
text field is initially empty.
– If the number of columns is not specified, the text field is sized
to fit the specified string

Prepared by Renetha J.B. 31

Downloaded from Ktunotes.in


JTextField(contd.)
• JTextField generates events in response to user interaction.
– For example, an ActionEvent is fired when the user presses
ENTER.
– A CaretEvent is fired each time the caret (i.e., the cursor)
changes position.
• CaretEvent is packaged in javax.swing.event
• To obtain the text currently in the text field, call getText( )

Prepared by Renetha J.B. 32

Downloaded from Ktunotes.in


JTextField(contd.)
// A simple Swing application.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/* <object code="SwingText" width=220 height=90>
</object>
*/
public class SwingText extends JApplet implements ActionListener
{ JLabel jlab;
JTextField jtf;

Prepared by Renetha J.B. 33

Downloaded from Ktunotes.in


private void makeGUI()
{ setLayout(new FlowLayout());
jlab = new JLabel(" Swing is powerful GUI");
add(jlab);
jtf = new JTextField(15);
jtf.addActionListener(this);
add(jtf);
}
public void actionPerformed(ActionEvent ae)
{
showStatus(jtf.getText());
}

Prepared by Renetha J.B. 34

Downloaded from Ktunotes.in


public void init()
{ try { SwingUtilities.invokeAndWait(new Runnable ()
{
public void run()
{
makeGUI(); }
});
} catch(Exception exc)
{ System.out.println("Can't create because of "+ exc); }
}
COMPILE USING
}
javac SwingText.java
RUN
appletviewer SwingText.java
Prepared by Renetha J.B. 35

Downloaded from Ktunotes.in


JList
• In Swing, the basic list class is called JList.
• JList provides several constructors

JList(Object[ ] items)

• A JList generates a ListSelectionEvent when the user makes or


changes a selection or deselects an item. It is handled by
implementing ListSelectionListener
• ListSelectionListener interface specifies only one method,
called valueChanged(),

void valueChanged(ListSelectionEvent le)

Prepared by Renetha J.B. 36

Downloaded from Ktunotes.in


Jlist(contd.)
• We can change this behavior by calling setSelectionMode( ),
void setSelectionMode(int mode)
Here mode can be
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
• We can obtain the index of the item selected from list by
calling getSelectedIndex( ) :
int getSelectedIndex( )
– Indexing begins at zero. So, if the first item is selected, this
method will return 0. If no item is selected, –1 is returned.
• We can obtain the value associated with
• the selection by calling getSelectedValue( ):
Object getSelectedValue( )
Prepared by Renetha J.B. 37

Downloaded from Ktunotes.in


JComboBox
• Swing provides a combo box (a combination of a text field and
a drop-down list) through the JComboBox class.
• JComboBox constructor is:
JComboBox(Object[ ] items)
• Items can also be dynamically added to the list
of choices via the addItem( ) method:
void addItem(Object obj)
• To obtain the item selected in the list is to call
getSelectedItem( ) on the combo box.
Object getSelectedItem( )
Prepared by Renetha J.B. 38

Downloaded from Ktunotes.in


Class hierarchy of swing components

Prepared by Renetha J.B. 39

Downloaded from Ktunotes.in


Reference
• Herbert Schildt, Java: The Complete Reference, 8/e,
Tata McGraw Hill, 2011.

Prepared by Renetha J.B. 40

Downloaded from Ktunotes.in


CS205 Object Oriented Programming in
Java
Module 5 - Graphical User Interface and
Database support of Java
(Part 6)
Prepared by
Renetha J.B.
AP
Dept.of CSE,
Lourdes Matha College of Science and Technology

1
Prepared by Renetha J.B.

Downloaded from Ktunotes.in


Topics

JDBC overview
Creating and Executing Queries

create table

delete

Insert

select

Prepared by Renetha J.B. 2

Downloaded from Ktunotes.in


Introduction
• Programming Language -Java
– for coding, developing interfaces(front end of an
application )
• Database – MySQL , Oracle , PostgreSQL
– For storing data- (back end of an application)
• Different types- relational database, object based
database etc.
– Relational database
• Tabular structure
• E.g. - Oracle, Microsoft Access, MySQL, PostgreSQL,
MongoDB etc
• SQL- Structured Query Language
– SQL statements are used to perform operations on a
database. We can insert , delete, update and retrieve data in
database using SQL statements. Prepared by Renetha J.B. 3

Downloaded from Ktunotes.in


JDBC overview
• JDBC stands for “Java DataBase Connectivity”.

• JDBC API (Application Programming Interface) is a Java


API that can access any kind of tabular data, especially
data stored in a Relational database.

• JDBC is used for executing SQL statements from Java


program.

• With the help of JDBC API, we can insert, update, delete


and fetch data from the database.

Prepared by Renetha J.B. 4

Downloaded from Ktunotes.in


Why JDBC?
• Before JDBC, ODBC(Open DataBase Connectivity) 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 unsecure).

– That is why, Java has defined its own API (JDBC API) that
uses JDBC drivers (written in Java language).

• If our application is using JDBC API to interact with the


database, then we need not change much in our code even
if we change the database of our application.
Prepared by Renetha J.B. 5

Downloaded from Ktunotes.in


Advantage of JDBC
• JDBC standardizes how to do many of the operations
like
– connect to the database,
– query the database,
– update the database, and
– call stored procedures.

Prepared by Renetha J.B. 6

Downloaded from Ktunotes.in


JDBC architecture
• JDBC architecture can be classified in 2 broad
categories:-

1. JDBC API

2. JDBC Drivers

Prepared by Renetha J.B. 7

Downloaded from Ktunotes.in


Java-JDBC API -JDBC Driver- Database
• Java – programming language – coding- Front end

• The JDBC API defines a set of interfaces and classes that all
major database providers follow, so that using JDBC API,
Java developers can connect to many Relational Database
Management Systems (RDBMS).

– JDBC API uses JDBC drivers to connect with the


database.

• A JDBC driver is a software component that enables a Java


application to interact with specific database.

• Database – store data – Back end


Prepared by Renetha J.B. 8

Downloaded from Ktunotes.in


Prepared by Renetha J.B. 9

Downloaded from Ktunotes.in


Prepared by Renetha J.B. 10

Downloaded from Ktunotes.in


JDBC API
• The Java Database Connectivity (JDBC) API provides
universal data access from the Java programming language

• Using the JDBC API, we can access virtually any data source
like relational databases , spreadsheets etc. from Java.

• The JDBC API is comprised of two packages:

java.sql

javax.sql

• These packages contains classes and interfaces for JDBC API.

Prepared by Renetha J.B. 11

Downloaded from Ktunotes.in


JDBC API
• Some classes and interfaces in java.sql package which support
connectivity between Java and database are:

– DriverManager :-"DriverManager class" manages all the


Drivers found in JDBC environment, load the most
appropriate driver for connectivity.

– Connection: Connection interface objects which represents


connection and it's object also helps in creating object of
Statement, PreparedStatement etc.

– Statement : :-Statement interface object is used to execute


query and also store it's value to "ResultSet" object.
Prepared by Renetha J.B. 12

Downloaded from Ktunotes.in


JDBC API(contd.)
– PreparedStatement:- represents a precompiled SQL
statement .

– Callable Statement:-Callable statement support stored


procedure .

– ResultSet: it is used to store the result of SQL query. Java


application get the result of database from this ResultSet.

– SQLException:- SQLException class is used to represent


error or warning during access from database or during
connectivity.

Prepared by Renetha J.B. 13

Downloaded from Ktunotes.in


JDBC Drivers
• JDBC API uses JDBC drivers to connect with the database.

• JDBC drivers .All major vendors provide their own JDBC


drivers .

• A JDBC driver is a software component that enables a Java


application to interact with a database.

• JDBC drivers contain a set of java classes that enables to


connect to that particular database.

Prepared by Renetha J.B. 14

Downloaded from Ktunotes.in


JDBC Drivers
Types Of JDBC Drivers:
JDBC drivers are divided into four types or levels.

Type 1: Type 2:
• JDBC-ODBC • Native-
Bridge driver API/partly Java
(Bridge) driver (Native)

Type 3: Type 4:
• All Java/Net- • All
protocol driver Java/Native-
(Middleware) protocol driver
/Thin Driver
(Pure)

Prepared by Renetha J.B. 15

Downloaded from Ktunotes.in


Type 1 JDBC Driver
• The Type 1(JDBC-ODBC Bridge driver) driver translates all
JDBC calls into ODBC calls and sends them to the ODBC
driver
• Advantage
– The JDBC-ODBC Bridge allows access to almost any
database, since the database's ODBC drivers are already
available.

Prepared by Renetha J.B. 16

Downloaded from Ktunotes.in


Type 2 JDBC Driver
• Type 2 drivers(Native-API/partly Java driver) convert
JDBC calls into database-specific calls.

Prepared by Renetha J.B. 17

Downloaded from Ktunotes.in


Type 3 JDBC Driver
• Type 3 database driver(All Java/Net-protocol driver)
requests are passed through the network to the middle-tier
server.
• The middle-tier then translates the request to the database.

Advantage
This driver is fully written in Java
and hence portable.
It is suitable for the web.

Prepared by Renetha J.B. 18

Downloaded from Ktunotes.in


Type 4 JDBC Driver
• Type 4 drivers(Native-protocol/all-Java driver) uses
java networking libraries to communicate directly with
the database server.
• Advantage
– They are completely written in Java-platform independent.
– It is most suitable for the web.

Prepared by Renetha J.B. 19

Downloaded from Ktunotes.in


Java-Database connectivity
Basic Steps fo connecting Java and database
• Before we can create a java JDBC connection to the database,
we must first import the java.sql package using:-
import java.sql.*;

Steps for connecting Java and database are:


Load and register a database driver
Establish(create) a connection to the database
Create Statement object
Execute the SQL Statements
Process the result
Close the connection and Statement
Prepared by Renetha J.B. 20

Downloaded from Ktunotes.in


Prepared by Renetha J.B. 21

Downloaded from Ktunotes.in


• Steps to develop JDBC application:
1. Load and Register Driver
2. Establish the connection between java application and
database
3. Creation of statement object
4. Send and execute SQL query
5. Process Result from ResultSet
6. Close the connection and statement.

Prepared by Renetha J.B. 22

Downloaded from Ktunotes.in


Java Database Connectivity steps
1. Load or register a database driver
– We can load /register a driver in Java in one of two ways:
Class.forName(String driver)
DriverManager.registerDriver(new constructor of
the driver )
– We can load the driver class by calling Class.forName()
with the Driver class name as an argument or
DriverManager.registerDriver() with constructor of
the driver class as argument
• Once loaded, the Driver class creates an instance of itself.
• JDBC-ODBC Bridge driver is commonly used.
– Each database has its own driver.
– The JDBC Driver class for MySQL database are
com.mysql.jdbc.Driver
com.mysql.cj.jdbc.Driver Prepared by Renetha J.B. 23

Downloaded from Ktunotes.in


Java Database Connectivity

• The code for loading MySQL database driver from Java


Class.forName("com.mysql.cj.jdbc.Driver");
or
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

Class.forName("com.mysql.jdbc.Driver");

Or
DriverManager.registerDriver(new com.mysql.jdbc.Driver());

Prepared by Renetha J.B. 24

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
2. Establish the connection between Java application and
database
– The getConnection() method of DriverManager class is used to
establish connection with the database.
public static Connection getConnection(String url ,String name,
String password) throws SQLException

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

JDBC url password


username

Prepared by Renetha J.B. 25

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
• A JDBC URL provides a way of identifying a database so that
the appropriate driver will recognize it and establish a
connection with it.
The standard syntax for JDBC URLs is:
jdbc:<subprotocol>:<subname>
• A JDBC URL has three parts, which are separated by colons:
– jdbc is the protocol.
– <subprotocol> is usually the driver or the database connectivity
mechanism, which may be supported by one or more drivers.
– <subname> is the database.
– For example, to access a MySQL database through a JDBC-
ODBC bridge, one might use a URL such as the following:
jdbc:mysql://localhost:3306/ABC

Prepared by Renetha J.B. 26

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/databasename" , "username",
"password" );
The JDBC url used is
jdbc:mysql://localhost:3306/databasename
• Here jdbc is the API,
• mysql is the database,
• localhost is the server name on which mysql is running(we can
give IP address here)
• 3306 is the port number
• databasename is the name of the database created in MySQL
username Give the username of MySQL(root is the default
username. Other MySQL username also we can give here).
password Give the password of MySQL login given during
installation. Prepared by Renetha J.B. 27

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
3. Creating a Statement object
– Once a connection is established, we can interact with the
database.
– To execute SQL statements, we need to create a Statement
object from the Connection object by using the
createStatement() method.
– A Statement object is used to send and execute SQL statements
to a database.
Statement object= connectionobject. createStatement();
E.g.
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root" , "root123" );
Statement st = con.createStatement();
– Statement object st is used to send and execute SQL statements to
a database. Prepared by Renetha J.B. 28

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
4. Execute the SQL Statements
• To execute a SQL statement we use executeQuery() or
executeUpdate() method on Statement object.
The executeUpdate() method executes the CREATE,
INSERT, DELETE and UPDATE statements.
• E.g.:
st.executeUpdate("CREATE TABLE stud1(roll int, name
varchar(15))");
st.executeUpdate(“INSERT INTO student values(1, ’Anu’) ”);

The executeQuery() method executes a SELECT query


• it takes an SQL SELECT query string as an argument and
returns the result(output) as a ResultSet object.
• E.g.:
ResultSet rs=st.executeQuery(“SELECT rollno, name from
student”);
Prepared by Renetha J.B. 29

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
5. Process the Result (in the case of SELECT query only -To
Retrieve the Result)
– The result of SELECT query (retrieves data from database)
is stored in ResultSet object.
– To retrieve the data from the ResultSet object, we have to
use ResultSet’s getxxx() method (where xxx is the data
type. )
public int getxxx(int columnIndex):
public int getxxx(Stringt columnIndex):
• getInt() to retrieve a integer value.
• getString() method can be used to retrieve a string
value.
• getFloat() method can be used to retrieve a floating
point value.
Prepared by Renetha J.B. 30

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
Eg:
ResultSet rs=st.executeQuery(“SELECT rollno, name
from student”);
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
– Here rs contains all rollno and name rows in studenttable
– ResultSet cursor is initially positioned before the first
row;
• the first call to the method next() (rs.next()) moves the
cursor forward and makes the first row the current row)
• the second call to next() moves the cursor forward and makes
the second row as the current row, and so on.
Prepared by Renetha J.B. 31

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
• rs.getInt(1) will retrieve the value of first attribute in the
current row(getInt() is used because first attribute is rollno
which is integer)

• rs.getString(2) will retrieve the value of second attribute in the


current row(getString() is used because second attribute is
name which is character string)

Prepared by Renetha J.B. 32

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
ResultSet rs=st.executeQuery(“SELECT rollno, name from student”);
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
Working:
• Here rollno and name in all rows in student table are retrieved.
• ResultSet object rs maintains a cursor that is initially positioned
before the first row.
• When while(rs.next()) is first executed the cursor moves forward to
first row of result and prints the value of first attribute (rollno) and
second attribute(name)in first row in the result
• Next time while loop is executed, if second row is there, then rs.nex()
moves cursor to second row and prints the values in thar row.
• This continues until there is no more row in the result.
Prepared by Renetha J.B. 33

Downloaded from Ktunotes.in


Java Database Connectivity(contd.)
6. Close the connection and Statement

• Finally open connections need to be closed using close()


method as:
con.close()
st. close()

Prepared by Renetha J.B. 34

Downloaded from Ktunotes.in


MySQL
• MySQL is an open source database software.
– We can create databases, tables etc for storing data and we can
perform various database operations.
• Take mysqlshell and type:
\sql
\connect root@localhost
Enter password root123 (password given during installation)
• Create database
CREATE DATABASE ABC;
• Use the database for creating tables
USE ABC;
• Now you can do database operations in MySQL

Prepared by Renetha J.B. 35

Downloaded from Ktunotes.in


SQL Commands- CREATE TABLE
• CREATE TABLE tablename (atribute1 type, attribute2
type, attribute3 type Primary Key,….. atributen
type,constraints);
– Type can be
int
char(size)
varchar(size)
real
date
• E.g. CREATE TABLE person(name varchar(15) , age
int);

Prepared by Renetha J.B. 36

Downloaded from Ktunotes.in


SQL Commands- INSERT
• Insert rows(values of attribute) into table.
• INSERT INTO tablename (attribute,attribute..)
VALUES( value1,value2,….);
• If type of attribute is varchar or char its value should be
enclose in single quotes.
• E.g. Insert the following details into Person table
• Name is Anu Age 20, Name is Smith Age 10 ,
Name is Roy Age 70
INSERT INTO Person(name,age) VALUES(‘Anu’, 20);
INSERT INTO Person(name,age) VALUES(‘Smith’, 10);
INSERT INTO Person(name,age) VALUES(‘Roy’, 70);

Prepared by Renetha J.B. 37

Downloaded from Ktunotes.in


SQL Commands- DELETE
• Delete from table.
DELETE FROM tablename WHERE condition;
• Condition can be of the form:
Attribute=value Attribute<value Attribute>value
Attribute<=value Attribute>=value Attribute!=value
Attribute BETWEEN value 1AND value2
– If more than one condition is there, then they can be
combined using AND , OR as required.
E.g. . Remove details of persons having age 20
DELETE FROM Person WHERE age=20;
Remove details of persons having name Smith or age more
than 60
DELETE FROM Person where age>60 OR name=‘Smith’;
Prepared by Renetha J.B. 38

Downloaded from Ktunotes.in


SQL Commands - UPDATE
• To update or modify the contents in table.
UPDATE tablename SET attribute=value ,
attribute=value WHERE condition;
• Condition can be of the form:
Attribute=value Attribute<value Attribute>value
Attribute<=value Attribute>=value Attribute!=value
Attribute BETWEEN value 1AND value2
– If more than one condition is there, then they can be
combined using AND , OR as required.
E.g. Change the age of Roy to 25
UPDATE Person SET age=25 WHERE name=‘Roy’;

Prepared by Renetha J.B. 39

Downloaded from Ktunotes.in


SQL Commands - SELECT
• To select or retrieve content from table.
SELECT attribute1, attribute2,….. attributen FROM
tablename WHERE condition;
• Condition can be of the form:
Attribute=value Attribute<value Attribute>value
Attribute<=value Attribute>=value Attribute!=value
Attribute BETWEEN value 1AND value2
– If more than one condition is there, then they can be
combined using AND , OR as required.

E.g. Display name and age of persons with age more than 10.
SELECT name, age FROM Person WHERE age>10;
Prepared by Renetha J.B. 40

Downloaded from Ktunotes.in


Prepared by Renetha J.B. 41

Downloaded from Ktunotes.in


• Creating and Executing Queries
CREATE TABLE

DELETE

INSERT

SELECT.

Prepared by Renetha J.B. 42

Downloaded from Ktunotes.in


CREATE TABLE in MySQL from Java
• Write a Java program to create a table named Student
with fields rollno and name in the database ABC

Attribute Domain type


rollno int
name Varchar(15)

Prepared by Renetha J.B. 43

Downloaded from Ktunotes.in


Create table from Java
import java.sql.*;
public class CreateTableEg
{ public static void main(String args[]) throws ClassNotFoundException
{
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
//Create a statement object
Statement st=con.createStatement();
st.executeUpdate("CREATE TABLE Student (rollno int, name varchar(15))");
System.out.println("Table created");
con.close(); //Close the connection
}catch(SQLException e) { System.out.println("Error is " +e); }

} Prepared by Renetha J.B. 44


}
Downloaded from Ktunotes.in
INSERT row using Java
• Write a Java program to insert the following row into
Student table with fields rollno and name in the
database ABC
1 Anu

Prepared by Renetha J.B. 45

Downloaded from Ktunotes.in


INSERT row using Java
import java.sql.*;
public class InsertEg
{ public static void main(String args[]) throws ClassNotFoundException
{
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Open a connection
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
//Create a statement object
Statement st=con.createStatement();
st.executeUpdate("INSERT INTO Student(rollno,name) VALUES (1,'Anu')");
System.out.println(“Data inserted successfully");
con.close(); //Close the connection
}catch(SQLException e) { System.out.println("Error is " +e); }
}
} Prepared by Renetha J.B. 46

Downloaded from Ktunotes.in


• To access value of java variable inside the SQL command
use :
SinglequoteDoublequote+varaiable+DoublequoteSinglequote
• E.g.
int roll=2;
String nam=“Anu”;
st.executeUpdate("INSERT INTO Student(rollno,name)
VALUES('"+ roll +"' , '"+ nam +"' )");

Prepared by Renetha J.B. 47

Downloaded from Ktunotes.in


INSERT row using Java
• Write a Java program to insert details about n
students into Student table with fields rollno and
name in the database ABC

Prepared by Renetha J.B. 48

Downloaded from Ktunotes.in


INSERT n rows from Java
import java.sql.*; import java.util.*;
public class CreateTableEg
{ public static void main(String args[]) throws ClassNotFoundException
{ try { Scanner sc=new Scanner(System.in);
int roll,n,i;
String nam;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
Statement st=con.createStatement();
System.out.println("Enter how many students detail to be inserted");
n=sc.nextInt();
for(i=0;i<n;i++) con.close();
{ System.out.println("Enter the rollno"); }
roll=sc.nextInt(); catch(SQLException e)
System.out.println("Enter the name"); {
System.out.println(e);
sc.nextLine();
}
nam=sc.nextLine(); }
st.executeUpdate("INSERT INTO Student(rollno,name) }
values('"+ roll +"' , '"+ nam +"' )");
49
} System.out.println(“Data inserted successfully"); Prepared by Renetha J.B.

Downloaded from Ktunotes.in


DELETE rows using Java
• Write a Java program to delete details about students
into Student table with given roll number.

Prepared by Renetha J.B. 50

Downloaded from Ktunotes.in


DELETE rows using Java
import java.sql.*; import java.util.*;
public class InsertEg
{ public static void main(String args[]) throws ClassNotFoundException
{ int roll;
Scanner sc=new Scanner(System.in);
try { Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
Statement st=con.createStatement();

System.out.println("Enter the rollno of student to be deleted");


roll=sc.nextInt();
st.executeUpdate("DELETE FROM Student WHERE rollno='"+ roll +"' ");
System.out.println("Data deleted succesfully.");
con.close();
}catch(SQLException e) { System.out.println("Error is " +e); }
}
} Prepared by Renetha J.B. 51

Downloaded from Ktunotes.in


UPDATE rows using Java
• Write a Java program to update the name of roll
number 1 to John in Student table

Prepared by Renetha J.B. 52

Downloaded from Ktunotes.in


UPDATE rows using Java
import java.sql.*; import java.util.*;
public classUpdateEg
{ public static void main(String args[]) throws ClassNotFoundException
{ Scanner sc=new Scanner(System.in);
int roll; String nam;
try { Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
Statement st=con.createStatement();
System.out.println("Enter the rollno of student ");
roll=sc.nextInt(); sc.nextLine();
System.out.println("Enter the name of new student ");
nam=sc.nextLine();
st.executeUpdate("UPDATE Student SET name='"+ nam +"' WHERE
rollno='"+ roll +"' ");
con.close();
}catch(SQLException e) { System.out.println("Error is " +e); }
}
Prepared by Renetha J.B. 53
}
Downloaded from Ktunotes.in
SELECT rows using Java
• Write a Java program to list all names and roll numbers in
Student table

Prepared by Renetha J.B. 54

Downloaded from Ktunotes.in


SELECT rows Using Java
import java.sql.*; Import classes and interfaces
from java.sql package
public class InsertEg
{ public static void main(String args[]) throws ClassNotFoundException
{ Load the Driver for MySQL
try {
Class.forName("com.mysql.jdbc.Driver"); Establish
connection
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
Statement st=con.createStatement(); Create statement
ResultSet rs=st.executeQuery("SELECT rollno,name FROM student");
while(rs.next()) Execute Query and represent result as result set
{ System.out.println(rs.getInt(1)+" "+rs.getString(2));
} First column
Second column
con.close(); Close the connection
}catch(SQLException e) { System.out.println("Error is " +e); }
}
} Load the Driver for MySQL
Prepared by Renetha J.B. 55

Downloaded from Ktunotes.in


SELECT rowsUsing Java
import java.sql.*;
public class InsertEg
{ public static void main(String args[]) throws ClassNotFoundException
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select rollno,name from student");
while(rs.next())
{ System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
con.close();
}catch(SQLException e) { System.out.println("Error is " +e); }
}
}
Prepared by Renetha J.B. 56

Downloaded from Ktunotes.in


WORKING
• In this example we used MySQL as the database.
• Class.forName() is used for loading the Driver class
• Driver class: The driver class for the mysql database
is com.mysql.jdbc.Driver.
• DriverManager.getConnection() helps to establish the
connection
– Connection URL: The connection URL for the mysql
database is jdbc:mysql://localhost:3306/ABC 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 ABCis the database name. We may use
any database in MySQL here.
– 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.
Prepared by Renetha J.B. 57

Downloaded from Ktunotes.in


WORKING(contd.)
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root" , "root123" );
The JDBC url used is
jdbc:mysql://localhost:3306/ABC
• Here jdbc is the API,
• mysql is the database,
• localhost is the server name on which mysql is running(we can
also give IP address here)
• 3306 is the port number
• ABC is the database name created in MySQL (give your database
name here)
root is the username of MySQL(root is the default username .
Other MySQL username we can give here).
root123 is the password of MySQL given during installation(give
password you gave during installation) Prepared by Renetha J.B. 58

Downloaded from Ktunotes.in


WORKING(contd.)
Statement st=con.createStatement(); // con is the Connection object
– Statement object st is created from the Connection object con using the
method createStatement(). st can be used to send and execute SQL
statements to a database.
• To execute a SQL statement SELECT we use executeQuery()
method on Statement object .
• (Note:To execute a SQL commands CREATE TABLE, INSERT, DELETE ,
UPDATE we use executeUpdate() method on Statement object. )
ResultSet rs=st.executeQuery("SELECT rollno, name FROM
Student");
– SELECT command is executed using executeQuery() method on
Statement object st.
– Result of this SELECT is the rows containing all rollno and name
from the table Student in the form of ResultSet.
– ResultSet object rs maintains a cursor that is initially positioned
before the first row in the result of SELECT command. Prepared by Renetha J.B.
59

Downloaded from Ktunotes.in


WORKING(contd.)
ResultSet rs=st.executeQuery(“SELECT rollno, name FROM student”);
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
• ResultSet object rs maintains a cursor that is initially positioned
before the first row in the result.
• When while(rs.next()) is first executed the cursor moves forward to
first row of result
– System.out.println(rs.getInt(1)); prints the value of first attribute
(rollno)
– System.out.println(rs.getString(2)); prints the value of second
attribute (name) in the result
• Next time while loop is executed, if second row is there, then rs.nex()
moves cursor to second row and prints the values in that row.
• This continues until there is no more row in the result.
con.close(); closes the connection
Prepared by Renetha J.B. 60

Downloaded from Ktunotes.in


WORKING(contd.)
ResultSet rs=st.executeQuery(“SELECT rollno, name FROM student”);
while(rs.next())
{
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
}
Working:
• Here rollno and name in all rows in student table are retrieved.
• ResultSet object rs maintains a cursor that is initially positioned
before the first row in the result.
• When while(rs.next()) is first executed the cursor moves forward to
first row of result and prints the value of first attribute (rollno) and
second attribute(name)in first row in the result
• Next time while loop is executed, if second row is there, then rs.nex()
moves cursor to second row and prints the values in that row.
• This continues until there is no more row in the result.
con.close(); closes the connection
Prepared by Renetha J.B. 61

Downloaded from Ktunotes.in


WORKING(contd.)
• ClassNotFoundException , SQLException and other
exceptions may occur during these steps.
• ClassNotFoundException is thrown from main function
public static void main(String args[]) throws
ClassNotFoundException
• Using try catch other exceptions like SQLException can be
handled
try{

}catch(SQLException se)
{ }
catch(Exception e)
{ }
Prepared by Renetha J.B. 62

Downloaded from Ktunotes.in


SELECT rows based on conditionusing Java

• Write a Java program to list name of the student in


Student table having given roll number

Prepared by Renetha J.B. 63

Downloaded from Ktunotes.in


SELECT row based on condition Using Java
import java.sql.*;
import java.util.*
public class InsertEg
{ public static void main(String args[]) throws ClassNotFoundException
{ try { int roll;
Scanner sc=new Scanner(System.in);
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ABC" , "root","root123");
Statement st=con.createStatement();
System.out.println("Enter the rollno of student ");
roll=sc.nextInt();
ResultSet rs=st.executeQuery("SELECT name FROM student WHERE
rollno='"+ roll +"' ");
System.out.println("Name of student is “+rs.getString(1));

con.close();
}catch(SQLException e) { System.out.println("Error is " +e); }
}
Prepared by Renetha J.B. 64
}
Downloaded from Ktunotes.in
Summary
• Programming Language -Java
– for coding, developing interfaces(front end of an
application )
• Database – MySQL , Oracle , PostgreSQL
– For storing data- (back end of an application)
– Relational database -Tabular structure
• E.g. - Oracle, Microsoft Access, MySQL, PostgreSQL,
MongoDB etc
• SQL- Structured Query Language
– SQL statements are used to perform operations on a
database. CREATE TABLE, INSERT, DELETE, UPDATE,
SELECT

Prepared by Renetha J.B. 65

Downloaded from Ktunotes.in


Com.jd
bc.mys
ql.Drive
r

Prepared by Renetha J.B. 66

Downloaded from Ktunotes.in


Prepared by Renetha J.B. 67

Downloaded from Ktunotes.in


Prepared by Renetha J.B. 68

Downloaded from Ktunotes.in

You might also like