Swing Components – I: Introduction to JFC and Swing, Features of
the Java Foundation Classes, Swing API Components, JComponent
Class, Windows, Dialog Boxes, and Panels, Labels, Buttons, Check
Boxes, Menus, Pane, JScrollPane, Desktop pane, Scrollbars, Lists and
Combo Boxes, Text-Entry Components.
Swing Components – II: Toolbars, Implementing Action interface,
Colors and File Choosers, Tables and Trees, Printing with 2D API and
Java Print Service API. Schedules Tasks using JVM, Thread-safe
variables, Communication between threads. Event Handling: The
Delegation Event Model, Event classes (ActionEvent, FocusEvent,
InputEvent, ItemEvent, KeyEvent, MouseEvent, MouseWheelEvent,
TextEvent, WindowEvent) and various listener interfaces (ActionListener,
FocusListener, ItemListener, KeyListener, MouseListener,
MouseMotionListener, MouseWheelListener, TextListener,
WindowFocusListener, WindowListener)
JDBC: JDBC Introduction, JDBC Architecture, Types of JDBC Drivers,
The Connectivity Model, The java.sql package, Navigating the
ResultSet object’s contents, Manipulating records of a ResultSet
object through User Interface , The JDBC Exception classes, Database
Connectivity, Data Manipulation (using Prepared Statements, Joins,
Transactions, Stored Procedures), Data navigation.
Networking with JAVA: Overview of Networking, Working with URL,
Connecting to a Server, Implementing Servers, Serving multiple
Clients, Sending E-Mail, Socket Programming, Internet Addresses,
URL Connections. Accessing Network interface parameters, Posting
Form Data, Cookies, Overview of Understanding the Sockets Direct
Protocol. Introduction to distributed object system, Distributed
Object Technologies, RMI for distributed computing, RMI
Architecture, RMI Registry Service, Parameter Passing in Remote
Methods, Creating RMI application, Steps involved in running the RMI
application, Using RMI with Applets.
ICT role in 21st century education and it's challenges.
Tycs advance java sem 5 unit 1,2,3,4 (2017)
1. ADVANCE JAVA
TYBSC(CS) SEM 5
COMPILED BY : ST
302 PARANJPE UDYOG BHAVAN, NEAR KHANDELWAL SWEETS, NEAR THANE
STATION , THANE (WEST)
PHONE NO: 8097071144 / 8097071155
2. INDEX
Course:
USCS502
TOPICS Advanced Java Programming– I PGNO
Unit I Swing Components – I: Introduction to JFC and Swing, Features of
the Java Foundation Classes, Swing API Components, JComponent
Class, Windows, Dialog Boxes, and Panels, Labels, Buttons, Check
Boxes, Menus, Pane, JScrollPane, Desktop pane, Scrollbars, Lists and
Combo Boxes, Text-Entry Components.
1
Unit II Swing Components – II: Toolbars, Implementing Action interface,
Colors and File Choosers, Tables and Trees, Printing with 2D API and
Java Print Service API. Schedules Tasks using JVM, Thread-safe
variables, Communication between threads. Event Handling: The
Delegation Event Model, Event classes (ActionEvent, FocusEvent,
InputEvent, ItemEvent, KeyEvent, MouseEvent, MouseWheelEvent,
TextEvent, WindowEvent) and various listener interfaces (ActionListener,
FocusListener, ItemListener, KeyListener, MouseListener,
MouseMotionListener, MouseWheelListener, TextListener,
WindowFocusListener, WindowListener)
28
Unit III JDBC: JDBC Introduction, JDBC Architecture, Types of JDBC Drivers,
The Connectivity Model, The java.sql package, Navigating the
ResultSet object’s contents, Manipulating records of a ResultSet
object through User Interface , The JDBC Exception classes, Database
Connectivity, Data Manipulation (using Prepared Statements, Joins,
Transactions, Stored Procedures), Data navigation.
62
Unit IV Networking with JAVA: Overview of Networking, Working with URL,
Connecting to a Server, Implementing Servers, Serving multiple
Clients, Sending E-Mail, Socket Programming, Internet Addresses,
URL Connections. Accessing Network interface parameters, Posting
Form Data, Cookies, Overview of Understanding the Sockets Direct
Protocol. Introduction to distributed object system, Distributed
Object Technologies, RMI for distributed computing, RMI
Architecture, RMI Registry Service, Parameter Passing in Remote
Methods, Creating RMI application, Steps involved in running the RMI
application, Using RMI with Applets.
80
3. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
1 web:www.weit.in
UNIT 1
Introduction to JFC
JFC is short for Java Foundation Classes, which encompass a group of features for building
graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java
applications. It is defined as containing the features shown in the table below.
Feature Description
Swing GUI
Components
Includes everything from buttons to split panes to tables. Many
components are capable of sorting, printing, and drag and drop, to name
a few of the supported features.
Pluggable Look-and-
Feel Support
The look and feel of Swing applications is pluggable, allowing a choice
of look and feel. For example, the same program can use either the Java
or the Windows look and feel. Additionally, the Java platform supports
the GTK+ look and feel, which makes hundreds of existing look and
feels available to Swing programs. Many more look-and-feel packages
are available from various sources.
Accessibility API Enables assistive technologies, such as screen readers and Braille
displays, to get information from the user interface.
Java 2D API Enables developers to easily incorporate high-quality 2D graphics, text,
and images in applications and applets. Java 2D includes extensive APIs
for generating and sending high-quality output to printing devices.
Internationalization Allows developers to build applications that can interact with users
worldwide in their own languages and cultural conventions. With the
input method framework developers can build applications that accept
text in languages that use thousands of different characters, such as
Japanese, Chinese, or Korean.
Swing
The Swing classes are the next-generation GUI classes.
Swing components are purely written in Java.
Lightweight
―Pluggable‖ look and feel.
Swing is a huge set of components which includes labels, frames, tables, trees, and styled text
documents. Almost all Swing components are derived from a single parent called JComponent
which extends the AWT Container class. Swing is a layer on top of AWT rather than a
substitution for it.
The Java Foundation Classes consist of five major parts: AWT, Swing, and Accessibility, Java
2D, and Drag and Drop.
4. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
2 web:www.weit.in
Features of swing :
1. The Swing Components which includes everything from buttons to split panes to tables.
2. Swing components provide flexibility for nesting components. We can have a graphic in
a list, combo box in toolbox, panels in list box etc.
3. Swing components offer good look and feel regardless of OS. They look different than
OS components. But using the plugins support the same program can have either the Java
look and feel or the Windows look and feel.
4. Swing enables supportive technologies such as screen readers and Braille displays to get
information from the user interface.
5. Swing components follow Model-View-Controller Architecture/Design Pattern. Model
stores the contents and allows them to modify. View displays the contents in different
forms. Controller handles user input and interacts with view or model.
6. Java 2 Platform provides the ability to drag and drop between a Java application and a
native application.
7. The Java 2 API enables developers to easily incorporate high-quality 2D graphics, text,
and images in applications and in applets.
Disadvantages of Swing
1. Swing components are slower than AWT.
2. Swing components are not thread-safe. We may not get correct output if we modify the
model concurrently with the screen updater thread.
AWT VS SWING COMPONENTS OR HEAVYWEIGHT VS LIGHTWEIGHT
COMPONENTS
A heavyweight component is one that is associated with its OS's own native screen resource. A
lightweight component has no native resource of its own that's why it is lighter. Lightweight
component is painted onto a heavyweight component. All AWT components are heavyweight
and all Swing components are lightweight (except for the top-level components such as
JWindow, JFrame, JDialog, and JApplet).
A lightweight component can have transparent pixels; a heavyweight is always blurred.
A lightweight component can appear to be non-rectangular because of its ability to set
transparent areas; a heavyweight can only be rectangular.
Mouse events on a lightweight component fall through to its parent; mouse events on a
heavyweight component do not fall through to its parent.
When a lightweight component overlaps a heavyweight component, the heavyweight
component is always on top, regardless of the relative order of the two components.
"It is advisable that do not mix the heavyweight and lightweight components in a program."
5. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
3 web:www.weit.in
SWING CONATAINER PANES
Swing offers some top-level containers such as - JApplet, JDialog, and JFrame. There are some
problems for mixing lightweight and heavyweight components together in Swing, we can't just
add anything but first, we must get something called a "content pane," and then we can add
Swing components to that.
The different types of panes that are part of container are as follows -
The Root Pane
We don't directly create a JRootPane object. As an alternative, we get a JRootPane when we
instantiate JInternalFrame or one of the top-level Swing containers, such as JApplet, JDialog,
and JFrame.
It's a lightweight container used behind the scenes by these top-level containers. As the
preceding figure shows, a root pane has four parts :
1. The layered pane :
It Serves to position its contents, which consist of the content pane and the optional menu
bar. It can also hold other components in a specified order. JLayeredPane adds depth to
a JFC/Swing container, allowing components to overlap each other when needed.It
allows for the definition of a several layers within itself for the child components.
JLayeredPane manages its list of children like Container, but allows for the definition of
a several layers within itself.
2. The content pane :
The container of the root pane's visible components, excluding the menu bar.
3. The optional menu bar :
It is the home for the root pane's container's menus. If the container has a menu bar, we
generally use the container's setJMenuBar method to put the menu bar in the appropriate
place.
6. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
4 web:www.weit.in
4. The glass pane :
It is hidden, by default. If we make the glass pane visible, then it's like a sheet of glass
over all the other parts of the root pane. It's completely transparent.The glass pane is
useful when we want to be able to catch events or paint over an area that already contains
one or more components. We can display an image over multiple components using the
glass pane.
SWING COMPONENTS AND THE CONTAINMENT HIERARCHY
Swing application creates four commonly used Swing components :
1. A frame, or main window (JFrame).
2. An applet, called JApplet.
3. A panel, sometimes called a pane (JPanel).
4. Several other types of containers such as JScrollPane, JTabbedPane,
JInternalFrame etc.
Every top-level container indirectly contains an intermediate container known as a content pane.
The content pane contains, directly or indirectly, all of the visible components in the window's
GUI.
1. Component :
A component is an object having a graphical representation that can be displayed on the
screen and that can interact with the user. Examples of components are the buttons,
checkboxes, and scrollbars of a typical graphical user interface. It contains basic methods
such as setting the size, background/foreground colors that are associated with every GUI
element.
2. Container :
A container is a component that has the ability to hold other components. It also takes of
alignment and sizing of components that are present in it. This is done using Layout
manager classes.
3. Window :
A Window object is a top-level window with no borders and no menubar. The default
layout for a window is BorderLayout.
4. Frame :
A Frame is a top-level window with a title and a border.
5. Panel :
7. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
5 web:www.weit.in
Panel is the simplest container class. A panel provides space in which an application can
attach any other component, including other panels. The default layout manager for a
panel is the FlowLayout layout manager.
6. Applet :
An applet is a small program that is intended not to be run on its own, instead to be
embedded inside another application. The Applet class must be the superclass of any
applet that is to be embedded in a Web page or viewed by the Java Applet Viewer.
7. JFrame :
JFrame is an extended version of java.awt.Frame that adds support for the JFC/Swing
component architecture. Like all other JFC/Swing top-level containers, a JFrame contains
a JRootPane as its only child. The content pane provided by the root pane should, as a
rule, contain all the non-menu components displayed by the JFrame.
8. JApplet :
JApplet is an extended version of java.applet.Applet that adds support for the JFC/Swing
component architecture.
9. Canvas :
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the user. It
cannot be used to add/remove components.
The different types of swing components such as - JList, JButton etc. are derived
from JComponent.
JButton Class
Simple uses of JButton are very similar to Button. You create a JButton with a String as a label,
and then drop it in a window. Events are normally handled just as with a Button: you attach an
ActionListener via the addActionListener method.
JButton Constructor
JButton() Creates a button with no set text or icon.
JButton(Action a) Creates a button where properties are taken from the Action supplied.
JButton(Icon icon) Creates a button with an icon.
JButton(String text) Creates a button with text.
JButton(String text, Icon icon) Creates a button with initial text and an icon.
8. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
6 web:www.weit.in
Container class
Each GUI component can be contained only once. If a component is already in a container and
you try to add it to another container, the component will be removed from the first container and
then added to the second.
Each top-level container has a content pane that, generally speaking, contains (directly or
indirectly) the visible components in that top-level container's GUI.
Container class methods
add(Component) Adds the specified component to this container.
add(String, Component) Adds the specified component to this container.
countComponents() Returns the number of components in this panel.
deliverEvent(Event) Delivers an event.
getComponent(int) Gets the nth component in this container.
getComponents() Gets all the components in this container.
getLayout() Gets the layout manager for this container.
layout() Does a layout on this Container.
locate(int, int) Locates the component that contains the x,y position.
minimumSize() Returns the minimum size of this container.
preferredSize() Returns the preferred size of this container.
remove(Component) Removes the specified component from this container.
removeAll() Removes all the components from this container.
setLayout(LayoutManager) Sets the layout manager for this container.
Write a program to display a button on the screen and on the click of the button
change the background colour of applet to red using “Swing”.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class firstswing extends JApplet implements ActionListener
{
Container cp;
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
JButton b1=new JButton("Click Me");
cp.add(b1);
9. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
7 web:www.weit.in
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
cp.setBackground(Color.red);
}
}
/*<applet code=firstswing height=400 width=400></applet>*/
Execution
1. javac firstswing.java
2. appletviewer firstswing.java
NOTE
To obtain a container we use getContentPane() method.
By default the Layout followed by swing is BorderLayout, we can set the layout to
FlowLayout.
10. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
8 web:www.weit.in
Write a program to display the following
code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class second extends JApplet implements ActionListener
{
Container cp;
JLabel l1,l2;
JTextField t1,t2;
JButton b1;
@Override
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
l1=new JLabel("Enter Pet-Name");
l2=new JLabel("Display");
t1=new JTextField(20);
t2=new JTextField(20);
b1=new JButton("Click");
cp.add(l1);
cp.add(t1);
cp.add(l2);
cp.add(t2);
cp.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=t1.getText();
t2.setText(str);
}
11. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
9 web:www.weit.in
}
/*<applet code=second height=400 width=400></applet>*/
NOTE
By default every control stores a value in string format.
When the value is retrieve it is bydefault in string, and when you want to set a value, it
should be converted into string
Write a program to display the following.
code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class thirdCube extends JApplet implements ActionListener
{
Container cp;
JLabel l1,l2;
JTextField t1,t2;
JButton b1,b2;
@Override
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
l1=new JLabel("Enter Number");
l2=new JLabel("Result");
t1=new JTextField(10);
t2=new JTextField(10);
b1=new JButton("SQUARE");
b2=new JButton("CUBE");
cp.add(l1);
12. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
10 web:www.weit.in
cp.add(t1);
cp.add(l2);
cp.add(t2);
cp.add(b1);
cp.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int x=Integer.parseInt(t1.getText());
if(ae.getSource()==b1)
{
t2.setText(x*x+" ");
}
else
{
t2.setText(x*x*x+" ");
}
}
}
/*<applet code=thirdCube height=400 width=400></applet>*/
JCheckBox and JRadioButton
Using CheckBox, we can select multiple options simultaneously, where as
RadioButtons allows single selection from multiple options.
A checkbox is GUI field where use can make multiple choices for input. Each time
the user clicks it, its state swtiches between checked and unchecked. Radio buttons
are similar to checkboxes, but they are usually arranged in groups. When we click on
one radiobutton in the group the others automatically turn off. Checkboxes and radio
buttons are represented by JCheckBox and JRadio Button class object. Radio
buttons can be chained together using an instance of another class called
ButtonGroup.
A JCheckBox sends ItemEvents when it's clicked. Since a checkbox is a button, it
also fires ActionEvents when it becomes checked. We can change our choices until
we submit the form.
Write a program to display the following.
16. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
14 web:www.weit.in
t2.setText(x*x+"");
}
if(c1.getSelectedItem().toString().equals("CUBE"))
{
t2.setText(x*x*x+"");
}
}
if(ae.getSource()==b2)
{
t1.setText("");
t2.setText("");
}
}
public void itemStateChanged(ItemEvent ie)
{
int x=Integer.parseInt(t1.getText());
if(ie.getItem().equals("CUBE"))
{
t2.setText(x*x*x+"");
}
if(ie.getItem().equals("SQUARE"))
{
t2.setText(x*x+"");
}
}
}
/*<applet code=fifth height=400 width=400></applet>*/
JPanel
Like getContentPane, which is the main container, we have some secondary container,
which can hold other containers and control over itself.
JPanel is normally implemented, whenever we want to use more than one layout on the
main container.
A single application can use, more than one panel simultaneously.
17. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
15 web:www.weit.in
WAP to display the following (add panel in container)
code:
import javax.swing.*;
import java.awt.*;
public class ninth extends JApplet
{
Container cp;
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
JPanel jp=new JPanel();
jp.setLayout(new GridLayout(4,4));
for(int i=1;i<=16;i++)
{
jp.add(new JButton(i+""));
}
cp.add(jp);
cp.add(new JTextField(20));
}
}
/*<applet code=ninth height=400 width=400></applet>*/
MENU BAR
A Menu Bar is a set of Choices and subchoices that allow the user to choose from any one of the
saving option. A list of other option component a user can choose in a menu bar. To create a
menubar first we need to import list of packages that required for creating a menu bar in an
application. We defined a class name ' TMenu ' extends JFrame. We define a constructor that is
18. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
16 web:www.weit.in
used to create a JFrame with a specified size of 600*550. The JMenuBar is used to control the
list of bar at the top of window, this includes File, Edit etc. JMenuBar is positioned at the
menubar in the JFrame.The MenuBar is set at the JMenuBar. We define and add dropdown
menu in the menubar.
jButton1.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jButton1ActionPerformed(evt); // calls user-method } });
jButton1.addActionListener(new java.awt.event.ActionListener():
This is used to register an instance of the event handler class as a listener on components. public
void actionPerformed(java.awt.event.ActionEvent evt): The program must register this object as
an action listener the component source, using the addActionListener method. When the user
clicks the onscreen component, the component fires an action event. This results in the
invocation of the action listener's actionPerformed method. The single parameter to the method
is an ActionEvent object that gives information about the event and its source.
JLists
public interface JList extends Collection
An ordered collection (also known as a sequence). The user of this interface has precise control
over where in the list each element is inserted. The user can access elements by their integer
index (position in the list), and search for elements in the list.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of
elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if
they allow null elements at all. It is not inconceivable that someone might wish to implement a
list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert
them, but we expect this usage to be rare.
The List interface places additional stipulations, beyond those specified in the Collection
interface, on the contracts of the iterator, add, remove, equals, and hashCode methods.
Declarations for other inherited methods are also included here for convenience.
19. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
17 web:www.weit.in
WAP to display the following
code:
import javax.swing.JList;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.JLabel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class AddJListIntoJFrame
{
static JLabel l1 = new JLabel();
//Create contents for JList
static String[]listContents={"Honda","Toyota","Ford","Ferrari","Cooper"};
//Create a JList with it contents
static JList myList=new JList(AddJListIntoJFrame.listContents);
public static void main(String[]args)
{
//Create a JFrame with title ( Add JList into JFrame )
JFrame frame=new JFrame("Add JList into JFrame");
//Set layout for JFrame
frame.setLayout(new FlowLayout());
//Add JList into JFrame
frame.add(AddJListIntoJFrame.myList);
frame.add(AddJListIntoJFrame.l1);
//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set JFrame size
frame.setSize(400,400);
20. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
18 web:www.weit.in
//Make JFrame visible. So we can see it.
frame.setVisible(true);
myList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event)
{
AddJListIntoJFrame.l1.setText(myList.getSelectedValue().toString());
}
});
}
}
JLIST WITH FIXED SET OF CHOICES
1. Building JList: Pass Strings to JList Constructor :
To use a JList, just supply an array of strings to the JList constructor. Like an AWT List, JList
does not have a way to directly add or remove elements, once the JList is created. For that, we
have to use a List Model. But the approach here is easier in the common case of displaying a
fixed set of choices.
String tOpt = { "Opt 1", ... , "Opt N"};
JList tOptList = new JList(tOpt);
2. Setting Visible Rows :
We can set the number of rows using the setVisibleRowCount method. Though, this is not
useful until the JList has scrollbars. As in Swing, scrollbars are supported only by dropping the
component in a JScroll Pane.
optionList.setVisibleRowCount(4);
JScrollPane toptPane = new JScrollPane(tOptList);
someContainer.add(toptPane);
3. Handling Events :
JLists generate List Selection events, for that we attach a ListSelectionListener, which uses the
valueChanged method. A single click generates three events: one for the deselection of the
originally selected entry, one to show the selection is moving, and one for the selection of the
new entry. In the first two cases, the List Event's getValueIsAdjusting method returns true. If
the JList supports multiple selections (use setSelectionMode to specify this; default is single
selections), we use get Selected Values and get Selected Indexes to get an array of the selections.
21. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
19 web:www.weit.in
Component Organizers
The JFC provides a number of user interface elements you can use for organizing the contents of
windows: panels, tabbed panes, split panes, and scroll panes. Panels and panes can be used to
organize windows into one or more viewing areas. A panel is a JFC component that you can use
for grouping other components inside windows or other panels.
A pane is a collective term used for scroll panes, split panes, and tabbed panes, among others.
Panes provide a client area where you can offer control over which user interface elements users
see. For instance, a scroll pane enables the viewing of different parts of a client area; a tabbed
pane enables users to choose among screen-related client areas; and a split pane enables users to
allocate the proportions of a larger viewing area between two client areas.
Lower-Level Containers
Panels
Like getContentPane, which is the main container, we have some secondary container,
which can hold other containers and control over itself.
JPanel is normally implemented, whenever we want to use more than one layout on the
main container.
A single application can use, more than one panel simultaneously.
22. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
20 web:www.weit.in
In contrast to scroll panes and tabbed panes, which typically play an interactive role in an
application, a panel simply groups components within a window or another panel. Layout
managers enable you to position components visually within a panel
refer to example from jpanel
Scroll Panes
In some cases, the amount of data exceeds the entire window size, because of which, the
data gets shrinked or fruncated.
To avoid such situation we can use JScrollPane container class.
wap to illustrate scrollpanel
code:
import javax.swing.*;
import java.awt.*;
public class scrollpanel extends JApplet
{
Container cp;
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
JPanel jp=new JPanel();
jp.setLayout(new GridLayout(40,40));
JTextArea jta = new JTextArea("anbncndnenenfngnhninj",3,3);
JScrollPane jsp=new JScrollPane(jta);
cp.add(jsp);
}
}
/*<applet code=scrollpanel height=400 width=400></applet>*/
A scroll pane is a specialized container offering vertical or horizontal scrollbars (or both) that
enable users to change the visible portion of the window contents.
23. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
21 web:www.weit.in
Scroll Pane in a Document Window
You can choose whether a scroll pane always displays scrollbars or whether they appear
only when needed.
Unless you have a compelling reason to do otherwise, use the default setting for
horizontal scrollbars, which specifies that they appear only when needed.
Display a horizontal scrollbar if users can't see all the information in the window pane--
for instance, in a word-processing application that prepares printed pages, users might
want to look at the margins as well as the text.
If the data in a list is known and appears to fit in the available space (for example, a
predetermined set of colors), you still need to place the list in a scroll pane. Specify that a
vertical scrollbar should appear only if needed. For instance, if users change the font, the
list items might become too large to fit in the available space, and a vertical scrollbar
would be required.
If the data in a scroll pane sometimes requires a vertical scrollbar in the normal font,
specify that the vertical scrollbar always be present. This practice prevents the distracting
reformatting of the display whenever the vertical scrollbar appears or disappears.
Scrollbars are obtained by placing the component, such as a text area, inside a scroll
pane.
Scrollbars
A scrollbar is a component that enables users to control what portion of a document or
list (or similar information) is visible on screen. In locales with left-to-right writing
systems, scrollbars appear along the bottom and the right sides of a scroll pane, a list, a
combo box, a text area, or an editor pane. In locales with right-to-left writing systems,
such as Hebrew and Arabic, scrollbars appear along the bottom and left sides of the
relevant component. By default, scrollbars appear only when needed to view information
that is not currently visible, although you can specify that the scrollbar is always present.
24. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
22 web:www.weit.in
The size of the scroll box represents the proportion of the window content that is
currently visible. The position of the scroll box within the scrollbar represents the
position of the visible material within the document. As users move the scroll box, the
view of the document changes accordingly. If the entire document is visible, the scroll
box fills the entire channel.
Both horizontal and vertical scroll boxes have a minimum size of 16 x 16 pixels so that
users can still manipulate them when viewing very long documents or lists.
At either end of the scrollbar is a scroll arrow which is used for controlling small
movements of the data.
The following figure shows horizontal and vertical scrollbars. Each scrollbar is a
rectangle consisting of a textured scroll box, a recessed channel, and scroll arrows.
Vertical and Horizontal Scrollbars
Do not confuse the scrollbar with a slider, which is used to select a value.
Users drag the scroll box, click the scroll arrows, or click in the channel to change the
contents of the viewing area. When users click a scroll arrow, more of the document or
list scrolls into view. The contents of the pane or list move in increments based on the
type of data. When users hold down the mouse button, the pane or list scrolls
continuously.
Scroll the content approximately one pane at a time when users click in the scrollbar's
channel. Leave one small unit of overlap from the previous information pane to provide
context for the user. For instance, in scrolling through a long document, help users
become oriented to the new page by providing one line of text from the previous page.
Scroll the content one small unit at a time when users click a scroll arrow. (The smallest
unit might be one line of text, one row in a table, or 10 to 20 pixels of a graphic.) The unit
controlled by the scroll arrows should be small enough to enable precise positioning of
the text or graphic but not so small that users must spend an impractical amount of time
using the scroll arrow.
25. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
23 web:www.weit.in
Ensure that the scroll speed is fairly constant when users click the scroll arrows. Ensure
that scrollbar controls run quickly yet enable users to perform the operation without
overshooting the intended location. The best way to determine the appropriate scrolling
rate is to test the scrolling rate with users who are unfamiliar with your application.
Ensure that the scrolling rate is appropriate across different processor speeds.
Place scrollbars in the orientation that is suitable for the writing system of your target
locale. For example, in the left-to-right writing systems (such as English and other
European languages), the scrollbars appear along the right side of the scroll pane or other
component. In other locales, they might appear along the left side of the scroll pane.
Tabbed Panes
In some application, there may be need to implement multiple interfaces on a single
window.
To implement this, we have to use JTabbedPane container class.
By default it follows CardLayout fashion.
In this type of layout, one window is at the foreground, whereas rest of the windows are
stabbed at the background.
WAP to implement JTabbedPane in the container.
code:
import javax.swing.*;
import java.awt.*;
public class fourteenth extends JApplet
{
Container cp;
public void init()
{
cp=getContentPane();
JTabbedPane jt=new JTabbedPane();
JPanel jp1=new JPanel();
jp1.add(new JButton("Click"));
JPanel jp2=new JPanel();
26. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
24 web:www.weit.in
jp2.add(new JRadioButton("r u there"));
jt.addTab("Button",jp1);
jt.addTab("RadioButton",jp2);
cp.add(jt);
}
}
/*<applet code=fourteenth height=400 width=400></applet>*/
A TabbedPane is a container that enables users to switch between several content panes that
appear to share the same space on screen. (The panes are implemented as JPanel components.)
The tabs themselves can contain text or images or both.
A typical tabbed pane appears with tabs displayed at the top, but the tabs can be displayed on any
of the four sides. If the tabs cannot fit in a single row, additional rows are created automatically.
Note that tabs do not change position when they are activated. For the first row of tabs, there is
no separator line between the active tab and the pane.
The following figure shows the initial content pane in the JFC-supplied color chooser. Note that
the tabbed pane is displayed within a dialog box that uses the borders, title bar, and window
controls of the platform on which its associated application is running.
Text Components
Swing gives us sophisticated text components; from plain text entry boxes to HTML
interpreters.The JTextComponent class is the foundation for Swing text components.
This class provides customizable features for all of its subclass such as a model,
known as a document, that manages the component's content. When we add or
remove text from a JTextField or a JTextArea, the corresponding Document is
changed. A view, which displays the component on screen, a controller, known as an
editor kit, that reads and writes text and implements editing capabilities with actions.
lt also support for infinite undo and redo.
JTextArea is a multiline text editor;
JTextField is a simple single-line text editor .
Both JTextField and JTextArea derive from the JTextComponent class.
They provide methods for setting and retrieving the displayed text, specifying
whether the text is "editable" or read-only, manipulating the cursor position within
the text, and manipulating text selections.
Swing text components display text and optionally allow the user to edit the text.
Programs need text components for tasks ranging from the straightforward (enter a
word and press Enter) to the complex (display and edit styled text with embedded
images in an Asian language).
Swing provides six text components, along with supporting classes and interfaces that
meet even the most complex text requirements. In spite of their different uses and
capabilities, all Swing text components inherit from the same superclass,
27. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
25 web:www.weit.in
JTextComponent, which provides a highly-configurable and powerful foundation for
text manipulation.
The following figure shows the JTextComponent hierarchy.
WAP to implement Text-Entry components
code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class texten extends JApplet implements ActionListener
{
Container cp;
29. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
27 web:www.weit.in
/*<applet code=texten height=400 width=400></applet>*/
JPasswordField Constructor
JPasswordField()
Constructs a new JPasswordField, with a default document, null starting text string, and 0
column width.
JPasswordField(Document doc, String txt, int columns)
Constructs a new JPasswordField that uses the given text storage model and the given
number of columns.
JPasswordField(int columns)
Constructs a new empty JPasswordField with the specified number of columns.
JPasswordField(String text)
Constructs a new JPasswordField initialized with the specified text.
JPasswordField(String text, int columns)
Constructs a new JPasswordField initialized with the specified text and columns.
30. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
28 web:www.weit.in
UNIT 2
Swing Components – II
Color Chooser
Use the JColorChooser class to enable users to choose from a palette of colors. A color chooser
is a component that you can place anywhere within your program GUI. The JColorChooser API
also makes it easy to bring up a dialog (modal or not) that contains a color chooser.
Here is a picture of an application that uses a color chooser to set the text color in a banner:
The color chooser consists of everything within the box labeled Choose Text Color. This is what
a standard color chooser looks like in the Java Look & Feel. It contains two parts, a tabbed pane
and a preview panel. The three tabs in the tabbed pane select chooser panels. The preview
panel below the tabbed pane displays the currently selected color.
The JColorChooser constructor in the previous code snippet takes a Color argument, which
specifies the chooser's initially selected color. If you do not specify the initial color, then the
color chooser displays Color.white.
A color chooser uses an instance of ColorSelectionModel to contain and manage the current
selection. The color selection model fires a change event whenever the user changes the color in
31. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
29 web:www.weit.in
the color chooser. The example program registers a change listener with the color selection
model so that it can update the banner at the top of the window.
WAP to demonstrate JColorChooser
code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class colorch extends JApplet implements ActionListener
{
JButton b1;
32. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
30 web:www.weit.in
Container cp;
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
b1=new JButton("pick to change the Background");
b1.addActionListener(this);
cp.add(b1);
}
public void actionPerformed(ActionEvent ae)
{
Color initialbg=cp.getBackground();
Color bg=JColorChooser.showDialog(null,"change Container
Background",initialbg);
cp.setBackground(bg);
}
}
/*<applet code=colorch height=600 width=600></applet>*/
Creating and Displaying the Color Chooser
Method or Constructor Purpose
JColorChooser()
JColorChooser(Color)
JColorChooser(ColorSelectionModel)
Create a color chooser. The default constructor creates a
color chooser with an initial color of Color.white. Use
the second constructor to specify a different initial
color. The ColorSelectionModel argument, when
present, provides the color chooser with a color
selection model.
Color showDialog(Component,
String, Color)
Create and show a color chooser in a modal dialog.
The Component argument is the parent of the dialog,
the Stringargument specifies the dialog title, and
the Color argument specifies the chooser's initial color.
JDialog createDialog(Component,
String,
boolean, JColorChooser,
ActionListener,
ActionListener)
Create a dialog for the specified color chooser. As
with showDialog, the Component argument is the
parent of the dialog and the String argument specifies
the dialog title. The other arguments are as follows:
the boolean specifies whether the dialog is modal,
the JColorChooser is the color chooser to display in the
dialog, the firstActionListener is for the OK button, and
the second is for the Cancel button.
33. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
31 web:www.weit.in
File Chooser
File choosers provide a GUI for navigating the file system, and then either choosing a file or
directory from a list, or entering the name of a file or directory. To display a file chooser, you
usually use the JFileChooser API to show a modal dialog containing the file chooser. Another way
to present a file chooser is to add an instance of JFileChooser to a container.
The JFileChooser API makes it easy to bring up open and save dialogs. The type of look and feel
determines what these standard dialogs look like and how they differ. In the Java look and feel,
the save dialog looks the same as the open dialog, except for the title on the dialog's window and
the text on the button that approves the operation.
WAP to demonstrate JFileChooser (for saving and opening)
34. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
32 web:www.weit.in
code:
import java.io.*;
import javax.swing.*;
public class FileChooser {
public static void main(String[] args)
{
JFileChooser chooser = new JFileChooser();
File f;
String filename;
chooser.showOpenDialog(null);
f = chooser.getSelectedFile();
filename = f.getName();
System.out.println("You have selected : " + filename + " for open");
//-------------------------------------
chooser.showSaveDialog(null);
f = chooser.getSelectedFile();
filename = f.getName();
System.out.println("You have selected : " + filename + " for save");
}
}
output:
You have selected : sid.cpp for open
You have selected : Text1.c for save
Creating and Showing the File Chooser
Method or Constructor Purpose
JFileChooser()
JFileChooser(File)
JFileChooser(String)
Creates a file chooser instance.
The File and String arguments, when present, provide the
initial directory.
int showOpenDialog(Component)
int showSaveDialog(Component)
int showDialog(Component,
String)
Shows a modal dialog containing the file chooser. These
methods return APPROVE_OPTION if the user
approved the operation and CANCEL_OPTION if the
user cancelled it. Another possible return value
is ERROR_OPTION, which means an unanticipated
error occurred.
Selecting Files and Directories
Method Purpose
void setSelectedFile(File)
File getSelectedFile()
Sets or obtains the currently selected file or (if
directory selection has been enabled) directory.
voidsetSelectedFiles(File[])
File[] getSelectedFiles()
Sets or obtains the currently selected files if the file
chooser is set to allow multiple selection.
void setFileSelectionMode(int)
void getFileSelectionMode()
Sets or obtains the file selection mode. Acceptable
values are FILES_ONLY (the
35. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
33 web:www.weit.in
boolean isDirectorySelectionEnabled()
boolean isFileSelectionEnabled()
default), DIRECTORIES_ONLY,
andFILES_AND_DIRECTORIES.
Interprets whether directories or files are selectable
according to the current selection mode.
void setMultiSelectionEnabled(boolean)
boolean isMultiSelectionEnabled()
Sets or interprets whether multiple files can be
selected at once. By default, a user can choose only
one file.
void setAcceptAllFileFilterUsed(boolean)
boolean isAcceptAllFileFilterUsed()
Sets or obtains whether the AcceptAll file filter is
used as an allowable choice in the choosable filter
list; the default value is true.
Dialog createDialog(Component) Given a parent component, creates and returns a
new dialog that contains this file chooser, is
dependent on the parent's frame, and is centered
over the parent.
JTable
It is a container class which allows us to accommodate data in rows and column format.
The columns are created using single dimensional arrays whereas, the data is occupied in
a two dimensional array.
To display the name of coumns, place the Jtable on the JScrollPane.
The table is bydefault editable, if you want you can turn it into an uneditable by
setEnabled method.
Swings JTable component displays two-dimensional arrangement of objects. Tables are very
common in user interfaces. Tables are intrinsically complex but JTable component hides much
of that complexity. We can produce fully functional tables with rich behavior by writing a few
lines of code. We can also write more code and customize the display and behavior of Table in
our applications.
Tables represent the information in rows and columns. This is useful for presenting financial
data or representing data from a relational database. Tables in Swing are incredibly powerful.
The JTable class represents a visual table component. A JTable is based on a TableModel,
from among the several supporting interfaces and classes in the javax.swing.table package.
WAP to display the following table.
36. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
34 web:www.weit.in
code:
import javax.swing.*;
import java.awt.*;
public class eleventh extends JApplet
{
Container cp;
JTable jt;
public void init()
{
cp=getContentPane();
String col[]={"Roll_No","Name"};
String data[][]={{"1","Gabbar"},{"2","Kalia"},{"3","Mogambo"}};
jt=new JTable(data,col);//sets columns and data array
JScrollPane jsp=new JScrollPane(jt);
jt.setEnabled(false);
cp.add(jsp);
}
}
/*<applet code=eleventh height=400 width=400></applet>*/
With the JTable class you can display tables of data, optionally allowing the user to edit the
data. JTable does not contain or cache data; it is simply a view of your data. Here is a picture of
a typical table displayed within a scroll pane:
37. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
35 web:www.weit.in
JTrees
With the JTree class, you can display hierarchical data. A JTree object does not actually contain
your data; it simply provides a view of the data. Like any non-trivial Swing component, the tree
gets data by querying its data model. Here is a picture of a tree:
As the preceding figure shows, JTree displays its data vertically. Each row displayed by the tree
contains exactly one item of data, which is called a node. Every tree has a root node from which
all nodes descend. By default, the tree displays the root node, but you can decree otherwise. A
node can either have children or not. We refer to nodes that can have children — whether or not
they currently have children — as branch nodes. Nodes that can not have children are leaf nodes.
Branch nodes can have any number of children. Typically, the user can expand and collapse
branch nodes — making their children visible or invisible — by clicking them. By default, all
branch nodes except the root node start out collapsed.
A specific node in a tree can be identified either by a TreePath, an object that encapsulates a
node and all of its ancestors, or by its display row, where each row in the display area displays
one node.
An expanded node is a non-leaf node that will display its children when all its ancestors
are expanded.
A collapsed node is one which hides them.
A hidden node is one which is under a collapsed ancestor.
NOTE
38. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
36 web:www.weit.in
Jtree container class helps to arrange files and folders in hierarchical format.
Every file and folder is termed as node.
The node where the tree starts from, is said to be as rootnode.
The nodes are created using DefaultMutableTreeNode class.
These classes can be obtained by importing a package, javax.swing.tree.*;
Constructors:
JTree(Hashtable ht) : Each element of hashtable is a childnode.
JTree(Object ob[]) : Each element of the array object is childnode.
JTree(Treenode tn) : Treenode tn is the root of the tree.
JTree(Vector v) : Elements of vector v is the childnode.
write a program to display the following
code:
import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;
public class twelevth extends JApplet
{
Container cp;
JTree jt;
public void init()
{
cp=getContentPane();
DefaultMutableTreeNode a=new DefaultMutableTreeNode("My Stuff");
DefaultMutableTreeNode b=new DefaultMutableTreeNode("Video");
DefaultMutableTreeNode c=new DefaultMutableTreeNode("Muzic");
DefaultMutableTreeNode d=new DefaultMutableTreeNode("Linkin Park");
DefaultMutableTreeNode e=new DefaultMutableTreeNode("Akcent");
a.add(b);
a.add(c);
c.add(d);
39. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
37 web:www.weit.in
c.add(e);
jt=new JTree(a);
cp.add(jt);
}
}
/*<applet code=twelevth height=400 width=400></applet>*/
DefaultMutableTreeNode(object obj)
o where ‗obj‘ is the object to be enclosed in this tree node.
void add(MutableTreeNode child)
o This method can be used to create the hierarchy of nodes .where ‗child‘ is the
mutable treenode this is to be added as a child to the current node.
Printing with 2D API
The Java 2D™ API provides two-dimensional graphics, text, and imaging capabilities for Java™
programs through extensions to the Abstract Windowing Toolkit (AWT). This comprehensive
rendering package supports line art, text, and images in a flexible, full-featured framework for
developing richer user interfaces, sophisticated drawing programs, and image editors. Java 2D
objects exist on a plane called user coordinate space, or just user space. When objects are
rendered on a screen or a printer, user space coordinates are transformed to device space
coordinates.
The Java 2D™ API maintains two coordinate spaces:
User space – The space in which graphics primitives are specified
Device space – The coordinate system of an output device such as a screen, window, or a
printer
User space is a device-independent logical coordinate system, the coordinate space that your
program uses. All geometries passed into Java 2D rendering routines are specified in user-space
coordinates.
All of the Swing and Java 2D™ graphics, including composited graphics and images, can be
rendered to a printer by using the Java 2D Printing API. This API also provides document
composition features that enable you to perform such operations as changing the order in which
pages are printed.
Rendering to a printer is like rendering to a screen. The printing system controls when pages are
rendered, just like the drawing system controls when a component is painted on the screen.
40. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
38 web:www.weit.in
The Java 2D Printing API is based on a callback model in which the printing system, not the
application, controls when pages are printed. The application provides the printing system with
information about the document to be printed, and the printing system determines when each
page needs to be imaged.
The following two features are important to support printing:
Job control – Initiating and managing the print job including displaying the standard
print and setup dialog boxes
Pagination – Rendering each page when the printing system requests it
When pages need to be imaged, the printing system calls the application‘s print method with an
appropriate Graphics context. To use Java 2D API features when you print, you cast
the Graphics object to a Graphics2D class, just like you do when you are rendering to the screen.
WAP to demonstrate Printing with 2D API (print "hello WE-IT")
42. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
40 web:www.weit.in
}
Java Print Service API
Java 2D ™ printing API supports page imaging, displays print and page setup dialogs, and
specifies printing attributes. Printing services is another key component of any printing
subsystem.
The Java™ Print Service (JPS) API extends the current Java 2D printing features to offer the
following functionality:
Application discovers printers that cater to its needs by dynamically querying the printer
capabilities.
Application extends the attributes included with the JPS API.
Third parties can plug in their own print services with the Service Provider Interface,
which print different formats, including Postscript, PDF, and SVG.
The Java Print Service API consists of four packages:
The javax.print package provides the principal classes and interfaces for the Java™ Print Service
API. It enables client and server applications to:
Discover and select print services based on their capabilities.
Specify the format of print data.
Submit print jobs to services that support the document type to be printed.
NOTE:
Programming has become more interactive with Java 2D API. You can add images, figures,
animation to your GUI and even pass visual information with the help of Java 2D API. You can
43. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
41 web:www.weit.in
easily use 2D within Swing components such as drop shadows since Swing is built on 2D
package.
Pluggable Look and Feel
The Java Swing supports the plugging between the look and feel features. The look and feel that
means the dramatically changing in the component like JFrame, JWindow, JDialog etc. for
viewing it into the several types of window. You can create your own look and feel using Synth
package. There are many of existing look and feels which are available to Swing programs
provided by GTK+ look and feel. Moreover, the look and feel of the platform can be specified by
the program while running and also to use Java look and feel can be specified by it.
The pluggable look and feel indicates that the whole look of the GUI element can be changed i.e.
both the visual representation and behavior of a GUI can be changed at the time of display of the
component. The new object which is created by the Swing application i.e. a new button by
instantiating the JButton class already knows that how to react to mouse movements and mouse
clicks. Some tasks are only performed by certain specialized classes like mouse handling that is
why there is no need to change the code to modify the look. However, if the code is contained by
the button itself that creates its visual representation then this code would be required to be
changed to modify the look and feel of the GUI. Due to this reason only Swing provides custom
look and feel.
Threads and Multithread
Process
A process is an instance of a computer program that is executed sequentially. It is a collection of
instructions which are executed simultaneously at the rum time. Thus several processes may be
associated with the same program. For example, to check the spelling is a single process in the
Word Processor program and you can also use other processes like printing, formatting,
drawing, etc. associated with this program.
Multiprocessing
Many task done simultaneously in PC.
Program is a set of instruction and a ―A process is a running instance of a program.
In Multiprocessing OS implements CONTEXT SWITICHING mechanism.
Here CPU is shared between different process:
E.g. A MS-Word application and MS-Excel application is opened simultaneously or in general
any two applications running simultaneously is multiprocessing.
44. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
42 web:www.weit.in
Thread
Thread is any part of the program under execution.
A thread is an entity within a process .
Example:in your java program main() is a thread and garbage collector is another thread.
When more than one thread execute concurrently in a single application, it is termed as
―Multithreading‖
Thread can be created in either of the following ways:
1. Extending Thread class.
2. Implementing Runnable Interface.
1. Extending the java.lang.Thread Class
For creating a thread a class have to extend the Thread Class. For creating a thread by this
procedure you have to follow these steps:
1. Extend the java.lang.Thread Class.
2. Override the run( ) method in the subclass from the Thread class to define the code executed
by the thread.
3. Create an instance of this subclass. This subclass may call a Thread class constructor by
subclass constructor.
4. Invoke the start( ) method on the instance of the class to make the thread eligible for
running.
2. Implementing the java.lang.Runnable Interface
The procedure for creating threads by implementing the Runnable Interface is as follows:
1. A Class implements the Runnable Interface, override the run() method to define the code
executed by thread. An object of this class is Runnable Object.
2. Create an object of Thread Class by passing a Runnable object as argument.
3. Invoke the start( ) method on the instance of the Thread class.
A thread is a lightweight process which exist within a program and executed to perform a
special task. Several threads of execution may be associated with a single process. Thus a
process that has only one thread is referred to as a single-threaded process, while a process with
multiple threads is referred to as a multi-threaded process.
In Java Programming language, thread is a sequential path of code execution within a program.
Each thread has its own local variables, program counter and lifetime. In single threaded runtime
environment, operations are executes sequentially i.e. next operation can execute only when the
previous one is complete. It exists in a common memory space and can share both data and code
of a program. Threading concept is very important in Java through which we can increase the
45. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
43 web:www.weit.in
speed of any application. You can see diagram shown below in which a thread is executed along
with its several operations with in a single process.
Main Thread
When any standalone application is running, it firstly execute the main() method runs in a one
thread, called the main thread. If no other threads are created by the main thread, then program
terminates when the main() method complete its execution. The main thread creates some other
threads called child threads. The main() method execution can finish, but the program will keep
running until the all threads have complete its execution.
WAP to demonstrate thread through Extending thread class.
class thread1
{
public static void main(String arg[])
{
mythread mt=new mythread();
for(int i=1;i<=5;i++)
{
System.out.println(i);
try
{
Thread.sleep( 500);
}
catch(Exception e)
{}
}
}
}
class mythread extends Thread
{
mythread()
{
48. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
46 web:www.weit.in
Constructor
Thread() Allocates a new Thread object.
Thread(Runnable target) Allocates a new Thread object.
Thread(Runnable target,String name) Allocates a new Thread object.
Thread(String name) Allocates a new Thread object.
Thread(ThreadGroup group,Runnable target) Allocates a new Thread object.
Thread(ThreadGroup group,Runnable target,
String name)
Allocates a new Thread object so that it has
target as its run object, has the specified name as
its name, and belongs to the thread group
referred to by group.
Thread(ThreadGroup group,Runnable target,
String name,long stackSize)
Allocates a new Thread object so that it has
target as its run object, has the specified name as
its name, belongs to the thread group referred to
by group, and has the specified stack size.
Thread(ThreadGroup group,String name) Allocates a new Thread object.
Multithreading :
Multithreading is a technique that allows a program or a process to execute many tasks
concurrently (at the same time and parallel). It allows a process to run its tasks in parallel mode
on a single processor system
In the multithreading concept, several multiple lightweight processes are run in a single
process/task or program by a single processor. For Example, When you use a word processor
you perform a many different tasks such as printing, spell checking and so on. Multithreaded
software treats each process as a separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple threads of
execution running concurrently. It allows a program to be more responsible to the user. When a
program contains multiple threads then the CPU can switch between the two threads to execute
them at the same time.
For example, look at the diagram shown as:
49. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
47 web:www.weit.in
In this diagram, two threads are being executed having more than one task. The task of each
thread is switched to the task of another thread.
Advantages of multithreading over multitasking :
Reduces the computation time.
Improves performance of an application.
Threads share the same address space so it saves the memory.
Context switching between threads is usually less expensive than between processes.
Cost of communication between threads is relatively low.
Life cycle of a thread
When you are programming with threads, understanding the life cycle of thread is very
valuable.
While a thread is alive, it is in one of several states.
By invoking start() method, it doesn‘t mean that the thread has access to CPU and start
executing straight away.
Several factors determine how it will proceed.
50. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
48 web:www.weit.in
1. Born state
After the creations of Thread instance the thread is in this state but before the start() method
invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state
A thread start its life from Runnable state. A thread first enters runnable state after the invoking
of start() method but a thread can return to this state after either running, waiting, sleeping or
coming back from blocked state also.On this state a thread is waiting for a turn on the processor.
51. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
49 web:www.weit.in
3. Running state
A thread is in running state that means the thread is currently executing.There are several ways
to enter in Runnable state but there is only one way to enter in Running state: the scheduler select
a thread from runnable pool.
4. Dead state
A thread can be considered dead when its run() method completes. If any thread comes on this
state that means it cannot ever run again.
5. Blocked, Suspended
A thread can enter in this state because of waiting the resources that are hold by another thread.
6. Sleeping
On this state, the thread is still alive but it is not runnable, it might be return to runnable state
later, if a particular event occurs. On this state a thread sleeps for a specified amount of time.
You can use the method sleep( ) to stop the running state of a thread.
7. Waiting
A thread waits for notification from another thread.The thread sends back to runnable state after
sending notification from another thread.
Some Important Methods defined in java.lang.Thread are shown in the table:
Method Return
Type
Description
currentThread() Thread Returns an object reference to the thread in which it
is invoked.
getName( ) String Retrieve the name of the thread object or instance.
start( ) Void Start the thread by calling its run method.
run( ) Void This method is the entry point to execute thread, like
the main method for applications.
sleep( ) Void Suspends a thread for a specified amount of time (in
milliseconds).
isAlive( ) Boolean This method is used to determine the thread is
running or not.
52. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
50 web:www.weit.in
activeCount( ) Int This method returns the number of active threads in
a particular thread group and all its subgroups.
interrupt( ) Void The method interrupt the threads on which it is
invoked.
yield( ) Void By invoking this method the current thread pause its
execution temporarily and allow other threads to
execute.
join( ) Void This method and join(long millisec) Throws
InterruptedException. These two methods are
invoked on a thread. These are not returned until
either the thread has completed or it is timed out
respectively.
WAP to create a moving banner using threads and applet with two
buttons(start & stop).
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class myapp2 extends Applet implements Runnable,ActionListener
{
String str;
Thread t1,t;
int x;
Button b1,b2;
public void init()
{
str="Hello";
t1=new Thread(this);
t1.start();
x=300;
b1=new Button("START");
b2=new Button("STOP");
t1.suspend();//Suspend function
b1.addActionListener(this);
b2.addActionListener(this);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b1)
t1.resume();
else
t1.suspend();
}
53. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
51 web:www.weit.in
public void run()
{
while(true)
{
if(x<0)
{x=300;}
x=x-20;
try{
t.sleep(200);
}
catch(Exception e){}
repaint();
}
}
public void paint(Graphics g)
{
g.drawString(str,x,100);
}
}
/*<applet code=myapp2 height=400 width=500></applet>*/
Output:
Thread Synchronization in Java
Sometimes, when two or more threads need shared resource, they need a proper
mechanism to ensure that the resource will be used by only one thread at a time.
The mechanism we use to achieve this is known as thread synchronization.
The thread synchronization is achieved through the synchronized keyword. The
statements which need to be synchronized should put into the synchronized block It is
also known as critical section.
55. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
53 web:www.weit.in
Daemon Thread or Service Thread
This type of thread executes continuously in the background.
In Java, any thread can be a Daemon thread. Daemon threads are like a service
providers for other threads or objects running in the same process as the daemon thread.
Daemon threads are used for background supporting tasks and are only needed while
normal threads are executing.
If normal threads are not running and remaining threads are daemon threads then the
interpreter exits.
setDaemon(true/false) : This method is used to specify that a thread is daemon thread.
public boolean isDaemon() : This method is used to determine the thread is daemon
thread or not
WAP to demonstrate Daemon thread
class daemoon
{
public static void main(Strinmg arg[])
{
try
{
mythread mt1=new mythread(s);
mt1.setDaemon(true);
mythread mt2=new mythread(s);
mythread mt3=new mythread(s);
56. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
54 web:www.weit.in
mt1.start();
mt2.start();
mt3.start();
}
catch(Exception e){}
}
}
class mythread extends Thread
{
public void run()
{
system.out.println(Thread.currentThread().isDaemon());
}
}
NOTE:
To turn an ordinary thread into a daemon thread, use setDaemon() method, whereas to
check weather a thread is daemon or not use isDaemon() method.
Thread Communication
Java provides a very efficient way through which multiple-threads can communicate with
each-other.
This way reduces the CPU‘s idle time i.e. A process where, a thread is paused running in
its critical region and another thread is allowed to enter (or lock) in the same critical
section to be executed.
This technique is known as Interthread communication which is implemented by some
methods.
These methods are defined in "java.lang" package.
WAP to demonstrate communication between thread.
class communication
{
public static void main(String arg[])throws Exception
{
ThreadB b=new ThreadB();
b.start();
synchronized(b)
{
System.out.println("I am calling wait()");
b.wait();
System.out.println("I got notification");
57. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
55 web:www.weit.in
Thread.sleep(500);
}
System.out.println(b.total);
}
}
class ThreadB extends Thread
{
int total=0;
public void run()
{
synchronized(this)
{
try{
Thread.sleep(500);
System.out.println("I am starting calculation");
for(int i=0;i<=10;i++)
{
total=total++;
}
}
catch(Exception e){}
System.out.println("I am giving a notification call");
notify();
}
}
}
Output:
58. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
56 web:www.weit.in
Scheduling Task
In some applications some task need to run periodically, for example a application of
report generating checks for new database entry after one day and make reports according
to the entries then save all entries in company's permanent record.
Method Description
wait( ) It indicates the calling thread to give up the monitor and go to sleep
until some other thread enters the same monitor and calls method
notify() or notifyAll().
notify( ) It wakes up the first thread that called wait() on the same object.
notifyAll( ) Wakes up (Unloack) all the threads that called wait( ) on the same
object. The highest priority thread will run first.
All these methods must be called within a try-catch block.
WAP to demonstrate Task Scheduling
import java.util.Timer.*;
import java.util.TimerTask.*;
class Task extends TimerTask
{
int count = 1;
public void run()
{
System.out.println(count+" : Mogambo khush hua");
count++;
}
}
class TaskScheduling
{
public static void main(String[] args)
{
Timer timer = new Timer();
// Schedule to run after every 3 second(3000 millisecond)
timer.schedule( new Task(), 3000);
}
}
59. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
57 web:www.weit.in
Event Handling
Overview of the Delegation Event Model
Ans:
The 1.1 event model is also called the "delegation" event model because event handling is
delegated to different objects and methods rather than having your Applet handle all the
events.
The idea is that events are processed by event listeners, which are separate objects that
handle specific types of events.
o Note: In order to use the delegation event model properly, the Applet should not
be the listener.
The listener registers and specifies which events are of interest (for instance mouse
events).
Only those events that are being listened for will be processed.
Each different event type uses a separate Event class.
Each different kind of listener also uses a separate class.
This model makes event handling more efficient because not all events have to be
processed and the events that are processed are only sent to the registered listeners rather
than to an entire hierarchy of event handlers.
This model also allows your Applet to be organized such that the application code and
the interface code (the GUI) can be separated.
Also, using different event classes allows the Java compiler to perform more specific type
error checking.
Design Goals
The primary design goals of the new model in the AWT are the following:
Simple and easy to learn.
Support a clean separation between application and GUI code.
Facilitate the creation of robust event handling code which is less error-prone (strong
compile-time checking)
Flexible enough to enable varied application models for event flow and propagation
For visual tool builders, enable run-time discovery of both events that a component
generates as well as the events it may observe
Support backward binary compatibility with the old model
Event Hierarchy
Events are no longer represented by a single Event class (like java.awt.Event) with
numeric ids, but instead by a hierarchy of event classes. Each event class is defined by
the data representing that event type or related group of events types.
Since a single event class may be used to represent more than one event type (i.e.
MouseEvent represents mouse up, mouse down, mouse drag, mouse move, etc), some
60. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
58 web:www.weit.in
event classes may also contain an "id" (unique within that class) which maps to its
specific event types.
The event classes contain no public fields; the data in the event is completely
encapsulated by proper get<Attr>()/set<Attr>() methods (where set<Attr>() only exists
for attributes on an event that could be modified by a listener).
Although these are the concrete set defined by the AWT, programs are free to define their
own event types by subclassing either java.util.EventObject or one of the AWT event
classes. Programs should choose event ID values which are greater than the constant:
o java.awt.AWTEvent.RESERVED_ID_MAX
Q: Event classes
Ans:
The Event class is obsolete and is available only for backwards compatilibility. It has been
replaced by the AWTEvent class and its subclasses.
Event is a platform-independent class that encapsulates events from the platform's Graphical
User Interface in the Java 1.0 event model. In Java 1.1 and later versions, the Event class is
maintained only for backwards compatibilty. The information in this class description is
provided to assist programmers in converting Java 1.0 programs to the new event model.
In the Java 1.0 event model, an event contains an id field that indicates what type of event it is
and which other Event variables are relevant for the event.
For keyboard events, key contains a value indicating which key was activated, and modifiers
contains the modifiers for that event. For the KEY_PRESS and KEY_RELEASE event ids, the
value of key is the unicode character code for the key. For KEY_ACTION and
KEY_ACTION_RELEASE, the value of key is one of the defined action-key identifiers in the
Event class (PGUP, PGDN, F1, F2, etc).
AWT event classes
The subclasses of ATW Event can be categorized into two groups - Semantic events and low-
level events
Semantic events directly correspond to high level user interactions with a GUI component.
Clicking of a button is an example of a semantic event.
Event classes are semantic classes.
1. ActionEvent ("do a command")
2. AdjustmentEvent ("value was adjusted")
3. ItemEvent ("item state has changed")
4. TextEvent("the value of the text object changed")
61. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
59 web:www.weit.in
Following event classes are low level event classes.
1. ComponentEvent (component resized, moved, etc.)
2. ContainerEvent (component got focus, lost focus)
3. FocusEvent
4. KeyEvent (component got key-press, key-release, etc.)
5. MouseEvent (component got mouse-down, mouse-move, etc.)
6. PaintEvent
7. WindowEvent
Q: Event Listeners Interfaces
Ans:
An EventListener interface will typically have a separate method for each distinct event type the
event class represents. So in essence, particular event semantics are defined by the combination
of an Event class paired with a particular method in an EventListener.
For example, the FocusListener interface defines two methods, focusGained() and focusLost(),
one for each event type that FocusEvent class represents.
The API attempts to define a balance between providing a reasonable granularity of Listener
interface types and not providing a separate interface for every single event type.
INTERFACE INTERFACE METHODS ADD METHOD EVENT
CLASS
ActionListener actionPerformed (ActionEvent) addActionListener() ActionEvent
AdjustmentListen
er
adjustmentValueChanged(Adjustm
entEvent)
addAdjustmentListen
er()
AdjustmentE
vent
ComponentListen
er
componentHidden(ComponentEven
t)
addComponentListen
er()
ComponentE
vent
componentMoved(ComponentEven
t)
componentResized(ComponentEve
nt)
componentShown(ComponentEven
t)
ContainerListener componentAdded(ComponentEvent
)
addContainerListener
()
ContainerEve
nt
componentRemoved(ComponentEv
62. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
60 web:www.weit.in
ent)
FocusListener focusGained(FocusEvent) addFocusListener() FocusEvent
focusLost(FocusEvent)
ItemListener itemStateChanged(ItemEvent) addItemListener() ItemEvent
KeyListener keyPressed(KeyEvent) addKeyListener() KeyEvent
keyReleased(KeyEvent)
keyTyped(KeyEvent)
MouseListener mouseClicked(MouseEvent) addMouseListener() MouseEvent
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionLis
tener
mouseDragged(MouseEvent) addMouseMotionList
ener()
MouseEvent
mouseMoved(MouseEvent)
Text:Listener textValueChanged(TextEvent) addText:Listener() TextEvent
WindowListener windowActivated(WindowEvent) addWindowListener() WindowEven
t
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)
Q: What is delegation event model?
Ans:
Event model is based on the concept of an 'Event Source' and 'Event Listeners'.
Any object that is interested in receiving messages (or events) is called an Event
Listener.
63. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
61 web:www.weit.in
Any object that generates these messages ( or events ) is called an Event Source.
Event Delegation Model is based on four concepts:
1. The Event Classes
2. The Event Listeners
3. Explicit Event Enabling
4. Adapters
The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.
Its concept is quite simple:
1. a source generates an event and sends it to one or more listeners.
2. In this scheme, the listener simply waits until it receives an event.
3. Once received, the listener processes the event and then returns.
The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events.
A user interface element is able to "delegate" the processing of an event to a separate
piece of code.
64. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
62 web:www.weit.in
UNIT 3
Design of JDBC:
The JDBC™ API was designed to keep simple things simple. This means that the JDBC
makes everyday database tasks easy.
ADVANTAGES OF JDBC
Providing Existing Enterprise Data :
With JDBC businesses can continue to use their installed databases and access
information even if it is stored on different database management systems.
Easy Enterprise Development :
With JDBC development of application has become an easier job which is also cost
effective along with JDBC API & Java API. JDBC made the process simple by hiding
details at the time to access different tasks of database. Majority of the work done
internally The JDBC API is very easy to learn, Inexpensive to maintain & easy to deploy.
No need of Configurations for Network Computers :
With JDBC there is no need of configuration on the client side centralizes software
maintenance. Driver of JDBC is written in the Java, so all the information needed to
make a connection is completely defined by the JDBC URL or by a DataSource object.
DataSource object is registered with a Java Naming and Directory Interface (JNDI) naming
service.
Full Access to Metadata :
The JDBC API provides metadata access that enables the development of sophisticated
applications.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access.
Two-tier Architecture for Data Access.
In the two-tier model, a Java application talks directly to the data source. This requires a
JDBC driver that can communicate with the particular data source being accessed. A
65. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
63 web:www.weit.in
user's commands are delivered to the database or other data source, and the results of
those statements are sent back to the user. The data source may be located on another
machine to which the user is connected via a network. This is referred to as a
client/server configuration, with the user's machine as the client, and the machine housing
the data source as the server. The network can be an intranet, which, for example,
connects employees within a corporation, or it can be the Internet.
In the three-tier model, commands are sent to a "middle tier" of services, which then
sends the commands to the data source. The data source processes the commands and
sends the results back to the middle tier, which then sends them to the user. MIS directors
find the three-tier model very attractive because the middle tier makes it possible to
maintain control over access and the kinds of updates that can be made to corporate data.
Another advantage is that it simplifies the deployment of applications. Finally, in many
cases, the three-tier architecture can provide performance advantages.
Three-tier Architecture for Data Access.
Until recently, the middle tier has often been written in languages such as C or C++,
which offer fast performance. However, with the introduction of optimizing compilers
that translate Java bytecode into efficient machine-specific code and technologies such as
Enterprise JavaBeans™, the Java platform is fast becoming the standard platform for
middle-tier development. This is a big plus, making it possible to take advantage of Java's
robustness, multithreading, and security features.
With enterprises increasingly using the Java programming language for writing server
code, the JDBC API is being used more and more in the middle tier of a three-tier
architecture. Some of the features that make JDBC a server technology are its support for
connection pooling, distributed transactions, and disconnected rowsets. The JDBC API is
also what allows access to a data source from a Java middle tier.
66. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
64 web:www.weit.in
JDBC driver
The JDBC API defines the Java interfaces and classes that programmers use to connect to
databases and send queries. A JDBC driver implements these interfaces and classes for a
particular DBMS vendor. The JDBC driver converts JDBC calls into a network or database
protocol or into a database library API call that makes communication with the database. This
translation layer provides JDBC applications with database autonomy. In the case of any back-
end database change, only we need to just replace the JDBC driver & some code modifications
are required. "The Java program that uses the JDBC API loads the specified driver for a
particular DBMS before it actually connects to a database. After that the JDBC DriverManager
class then sends all JDBC API calls to the loaded driver".
JDBC Driver Types
JDBC drivers are divided into four types or levels. The different types of jdbc drivers
are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: All Java/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Type 1 Driver - JDBC-ODBC bridge
67. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
65 web:www.weit.in
Advantage :
The JDBC-ODBC Bridge allows access to almost any database, since the database's
ODBC drivers are already available.
Disadvantages :
The Bridge driver is not coded completely in Java; So Type 1 drivers are not
portable.
It is not good for the Web Application because it is not portable.
It is comparatively slowest than the other driver types.
The client system requires the ODBC Installation to use the driver.
Type 2 :Driver - Native-API Driver
Drivers that are written partly in the Java programming language and partly in native code. These
drivers use a native client library specific to the data source to which they connect. Again,
because of the native code, their portability is limited. Oracle's OCI (Oracle Call Interface)
client-side driver is an example of a Type 2 driver.
The JDBC type 2 driver, also known as the Native-API driver, is a database driver
implementation that uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API.
68. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
66 web:www.weit.in
Advantage :
This type of divers are normally offer better performance than the JDBC-ODBC Bridge as
the layers of communication are less than that it and also it uses Resident/Native API
which is Database specific.
Disadvantage :
Mostly out of date now.
It is usually not thread safe.
This API must be installed in the Client System; therefore this type of drivers cannot be
used for the Internet Applications.
Like JDBC-ODBC Bridge drivers, it is not coded in Java which cause to portability
issue.
If we modify the Database then we also have to change the Native API as it is specific to
a database.
Type 3 : Driver - Network-Protocol Driver(MiddleWare Driver)
• Drivers that use a pure Java client and communicate with a middleware server using a
database-independent protocol. The middleware server then communicates the client's
requests to the data source.
• The JDBC type 3 driver, also known as the Pure Java Driver for Database Middleware,
is a database driver implementation which makes use of a middle tier between the calling
program and the database. The middle-tier (application server) converts JDBC calls
directly or indirectly into the vendor-specific database protocol.
69. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
67 web:www.weit.in
Advantage :
This type of drivers is the most efficient amongst all driver types.
This driver is totally coded in Java and hence Portable. It is suitable for the web
Applications.
This driver is server based, so there is no need for any vendor database library to be
present on client machines.
With this type of driver there are many opportunities to optimize portability,
performance, and scalability.
The Net protocol can be designed to make the client JDBC driver very small and fast to
load.
This normally provides support for features such as caching, load balancing etc.
Provides facilities for System administration such as logging and auditing.
This driver is very flexible allows access to multiple databases using one driver.
Disadvantage :
This driver It requires another server application to install and maintain. Traversing the
recordset may take longer, since the data comes through the back-end server.
Type 4 : Driver - Native-Protocol Driver(Pure Java Driver)
Drivers that are pure Java and implement the network protocol for a specific data source.
The client connects directly to the data source
This provides better performance than the type 1 and type 2 drivers as it does not have
the overhead of conversion of calls into ODBC or database API calls. Unlike the type 3
drivers, it does not need associated software to work
70. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
68 web:www.weit.in
Advantage :
The Performance of this type of driver is normally quite good.
This driver is completely written in Java to achieve platform independence and
eliminate deployment administration issues. It is most suitable for the web.
In this driver number of translation layers are very less i.e. type 4 JDBC drivers don't
need to translate database requests to ODBC or a native connectivity interface or to
pass the request on to another server.
We don't need to install special software on the client or server.
These drivers can be downloaded dynamically.
Disadvantage :
• With this type of drivers, the user needs a different driver for each database.
Connection to MS – Access:
First create MS-Access Database file then go through following steps
Step 1 : Go into start menu > click on Control Panel.
Step 2 : Double click on Administrative Tool, then Data Source (ODBC)
Step 3 : You will get following window
71. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
69 web:www.weit.in
Step 4 : Then click on add , you will following window
Step 5 : Select “MS Access Driver(*.mdb,*.accdb)” , then click on finish
Step 6 : Next window will appear, Just enter the “data source name” whatever you
want
Step 7 : Click on select, new window will appear, just select path of
MS-Access Database file
72. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
70 web:www.weit.in
Step 8 : Click on ok .
JDBC steps-CONNECTIVITY
1. Load the Driver
2. URL Connection
3. Establish Connection
4. Statement
5. Execute Query
6. Obtain Result
7. Close Connection
Write a JDBC program to retrieve all the details from the student table, and
display the results on the command prompt.
Program : one.java
import java.sql.*;
class one
{
public static void main(String[] arg)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from student");
while(rs.next())
{
73. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
71 web:www.weit.in
System.out.println(rs.getString("rno")+" "+rs.getString("name"));
}
st.close();
con.close();
}
catch(Exception e){}
}
}
Output of one.java:
Dynamic SQL statement
The SQL commands which are incomplete and depends upon user‘s input value, is
termed as dynamic SQL statement.
Prepared Statement
It is a class which helps the execution of dynamic SQL statement.
It provide us with a setString() method which has two parameters.
WAP to accept a name from user and display the details of that particular
students
Program : two.java
import java.sql.*;
class two
{
public static void main(String[] arg)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
74. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
72 web:www.weit.in
PreparedStatement st=con.prepareStatement("Select * from student where
name=?");
st.setString(1,arg[0]);
ResultSet rs=st.executeQuery();
while(rs.next())
{
System.out.println(rs.getString("rno")+" "+rs.getString("name"));
}
st.close();
con.close();
}
catch(Exception e){}
}
}
Output of two.java
SCROLLABLE RESULTSETS
The resultsets are limited in facility. The rows in the resultset could be accessed only in the
forward direction. We can't move back and forth in a resultset or jumping to a particular row
identified by a row number. Also, the resultsets were read-only in that there was no way for
inserting new rows into the resultset, updating a particular row, or deleting a particular row.
Scrollability refers to moving forwards or backwards through rows in a resultset. Positioning
refers to moving the current row position to a different position by jumping to a specific row.
These two features are provided by means of three additional method calls, one each for
createStatement ( ), prepareStatement ( ), and prepareCall ( ) methods. These new methods take
two new parameters namely, the resultSetType and resultSetConcurrency. The definition of
these new methods is as follows:
tConn.createStatement (int resultSetType, int resultSetConcurrency);
tConn.prepareStatement (String sql, int resultSetType, int resultSetConcurrency);
tConn.prepareCall (String sql, int resultSetType, int resultSetConcurrency);
The parameter resultSetType tells whether a resultset is scrollable or not. It can take one of the
following three values only :