SlideShare a Scribd company logo
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
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
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.
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."
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.
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 :
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.
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);
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.
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);
}
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);
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.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
11 web:www.weit.in
code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class fourth extends JApplet implements ActionListener,ItemListener
{
Container cp;
JCheckBox c1,c2;
JRadioButton r1,r2;
JTextField t1;
ButtonGroup bg;
public void init()
{
cp=getContentPane();
bg=new ButtonGroup();
cp.setLayout(new FlowLayout());
c1=new JCheckBox("Hockey");
c2=new JCheckBox("cricket");
r1=new JRadioButton("Male");
r2=new JRadioButton("Female");
t1=new JTextField(10);
bg.add(r1);
bg.add(r2);
cp.add(c1);
cp.add(c2);
cp.add(r1);
cp.add(r2);
cp.add(t1);
r1.addActionListener(this);
r2.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
{
t1.setText(ae.getActionCommand().toString());
}
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
12 web:www.weit.in
public void itemStateChanged(ItemEvent ie)
{
String st1= "";
t1.setText("");
if(c1.isSelected())
{
st1 = st1 +" "+ (c1.getText());
t1.setText(st1);
}
if(c2.isSelected())
{
st1 = st1 +" "+ (c2.getText());
t1.setText(st1);
}
}
}
/*<applet code=fourth height=400 width=400></applet>*/
NOTE
 To provide single selection within multiple options, we have to add those appropriate
control to a ButtonGroup.
WAP to display the following.
code:
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
13 web:www.weit.in
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class fifth extends JApplet implements ActionListener,ItemListener
{
Container cp;
JComboBox c1;
JLabel l1,l2,l3;
JTextField t1,t2;
JButton b1,b2;
String str;
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
l1=new JLabel("Enter Number");
l2=new JLabel("Select Operation");
l3=new JLabel("Result");
c1=new JComboBox();
c1.addItem("SQUARE");
c1.addItem("CUBE");
t1=new JTextField(20);
t2=new JTextField(20);
b1=new JButton("Calculate");
b2=new JButton("Clear");
cp.add(l1);
cp.add(t1);
cp.add(l2);
cp.add(c1);
cp.add(l3);
cp.add(t2);
cp.add(b1);
cp.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
c1.addItemListener(this);
}
public void actionPerformed(ActionEvent ae)
{
int x=Integer.parseInt(t1.getText());
if(ae.getSource()==b1)
{
if(c1.getSelectedItem().toString().equals("SQUARE"))
{
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.
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
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.
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);
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.
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.
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.
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.
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.
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();
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,
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;
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
26 web:www.weit.in
JTextField jt;
JPasswordField pf;
JFormattedTextField jfd,jfc,jfn,jfp;
JTextArea ta;
JButton b1;
@Override
public void init()
{
cp=getContentPane();
cp.setLayout(new FlowLayout());
jt=new JTextField(15);
pf=new JPasswordField(10);
pf.setEchoChar('*');
jfd=new JFormattedTextField(new java.util.Date());
jfd.setValue(new Date());
jfd.setColumns(10);
jfp=new JFormattedTextField(java.text.NumberFormat.getPercentInstance());
jfp.setValue(new Float("0.67"));
jfp.setColumns(5);
jfc=new JFormattedTextField(java.text.NumberFormat.getCurrencyInstance());
jfc.setValue(new Float("200"));
jfc.setColumns(5);
ta=new JTextArea(5,5);
b1=new JButton("Click");
cp.add(jt);
cp.add(pf);
cp.add(jfd);
cp.add(jfp);
cp.add(jfc);
cp.add(ta);
cp.add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
ta.append(jt.getText()+"n"+jfd.getValue()+"n"+pf.getSelectedText());
}
}
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.
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
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;
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.
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)
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
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.
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:
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
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);
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.
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")
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
39 web:www.weit.in
code:
import java.awt.*;
import java.awt.print.*;
public class print2D implements Printable
{
Font sfont=new Font("serif",Font.PLAIN,64);
public int print(Graphics g,PageFormat pf,int pageindex)
throws PrinterException
{
if(pageindex>0)
{
return NO_SUCH_PAGE;
}
Graphics2D g2=(Graphics2D)g;
g2.setFont(sfont);
g2.setColor(Color.red);
g2.drawString("Hello WE-IT",96,144);
return PAGE_EXISTS;
}
public static void main(String arg[])
{
PrinterJob job=PrinterJob.getPrinterJob();
job.setPrintable(new print2D());
if(job.printDialog())
{
try
{
job.print();
}
catch(Exception e){}
}
}
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
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.
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
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()
{
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
44 web:www.weit.in
start();
}
public void run()
{
for(int i=11;i<=15;i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
}
}
}
}
Output:
WAP to demonstrate thread by implementing Runnable Interface.
class thread2
{
public static void main(String arg[])
{
mythread mt=new mythread();
for(int i=1;i<=5;i++)
{
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
45 web:www.weit.in
System.out.println(i);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
class mythread implements Runnable
{
Thread t;
mythread()
{
t=new Thread(this);
t.start();
}
public void run()
{
for(int i=11;i<=15;i++)
{
System.out.println(i);
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
Output:
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:
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.
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.
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.
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();
}
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.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
52 web:www.weit.in
WAP to demonstrate synchronization.
class sync
{
public static void main(String arg[])
{
share s=new share();
mythread mt1=new mythread(s);
mythread mt2=new mythread(s);
mythread mt3=new mythread(s);
}
}
class mythread extends Thread
{
share p;
mythread(share s)
{
p=s;
start();
}
public void run()
{
p.doword(Thread.currentThread().getName());
}
}
class share
{
public synchronized void doword(String str)
{
for(int i=1;i<=5;i++)
{
System.out.println(str);
try
{
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
Output:
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);
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");
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:
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);
}
}
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
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")
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
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.
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.
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
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.
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
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.
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.
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
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
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
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())
{
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");
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 :
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
73 web:www.weit.in
 TYPE_FORWARD_ONLY : It specifies that a resultset is not scrollable, rows within it
can be advanced only in the forward direction.
 TYPE_SCROLL_INSENSITIVE : It specifies that a resultset is scrollable in either
direction but is insensitive to changes committed by other transactions or other
statements in the same transaction.
 TYPE_SCROLL_SENSITIVE : It specifies that a resultset is scrollable in either direction
and is affected by changes committed by other transactions or statements within the
same transaction.
The second parameter result Set Concurrency determines whether a resultset is updateable
or not and can take one of the two values only :
 ResultSet.CONCUR READONLY
 ResultSet.CONCUR UPDATABLE
Updateable Resultsets
Updateable resultsets means the ability to update the contents of specific row(s) in the
resultset and propagating these changes to the underlying database. Also the operations of
INSERT and DELETE are possible. New rows can be inserted into the underlying table and
existing rows can be deleted from both theresultset as well as the underlying table.
UPDATE Operation Through a Resultset :
The following are the steps involved in creating and using an updateable resultset :
1. To create an updateable resultset, the resultSetConcurrency parameter has to be
specified as ResulSet.CONCUR_UPDATABLE while defining the createStatement ( ),
preparedStatement ( ), or prepareCall ( ) method on the Connection object.
This is shown below:
Connection con = null;
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Con=DriverManager.getConnection("jdbc:oracle:thin:@training: 1521 :Oracle"," test",
"test");
Statement stmt = conn.create Statement (Resultset. TYPE_SCROLL
.SENSITIVE, ResultSet.CONCUR_UPDATEABLE);
String sql = “SELECT * FROM EMP”;
ResultSet rset = stmt.executeQuery(sql);
2. Use the updateInt() or updateString() etc. methods on the ResultSet object to set the values of
the resultset columns. The use of this method is as follows :
rset.updateFloat (2, new Value);
In above code 2 refers to the second column in the resultset and newValue is a variable
that holds a new value to which this column data is to be set to.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
74 web:www.weit.in
3. Use the updateRow ( ) method on the ResultSet object to circulate the
changes made to the resultset to the underlying database table and commit
them. This has to be done once for each row in the resultset that is changed.
This is shown below :
rset.updateRow();
JDBC METADATA
Metadata means data about data; in other word we can say that it is a short description about
detailed data. There are two interfaces that contain the metadata portion of the JDBC.
DatabaseMetadata provides information about the database as a whole. It provides methods
so that we can discover what a particular database and driver combination can do.
ResultSetMetadata is much more specific. It is used to find out about the types and properties
of the columns in a ResultSet. This means it can examine what kind of information was
returned by a database query or a method of DatabaseMetadata.
Generally we use JDBC metadata facilities for Obtaining a list of tables available in the
database and Obtaining information about the columns in those tables.
ResultSetMetaData
An object that can be used to get information about the types and properties of the columns in a
ResultSet object.
We can get the count of columns and name of columns in the ResulSet using getColumnCount()
and getColumnName() method.
Example:-
Program : three.java
import java.sql.*;
class three
{
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");
ResultSetMetaData rsmd=rs.getMetaData();
int col = rsmd.getColumnCount();
System.out.println("Number of Column : "+ col);
System.out.println("Columns Name: ");
for (int i = 1; i <= col; i++)
{
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
75 web:www.weit.in
String col_name = rsmd.getColumnName(i);
System.out.println(col_name);
}
st.close();
con.close();
}
catch(Exception e){}
}
}
Output of three.java
Write a JDBC program to display details of those employees who work in any
of the two department ID’s entered by the user through command line
argument.
Program : four.java
import java.sql.*;
class four
{
public static void main(String[] arg)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:mydsn");
PreparedStatement st=con.prepareStatement("select * from student where name=?
or name=?");
st.setString(1,arg[0]);
st.setString(2,arg[1]);
ResultSet rs=st.executeQuery();
while(rs.next())
{
System.out.println(rs.getString("rno")+" "+rs.getString("name"));
}
st.close();
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
76 web:www.weit.in
con.close();
}
catch(Exception e){}
}
}
Output of four.java
General Info
• Importing a package Java.sql :Network Interface for communicating between front -end
application and database.
• Inside the try block we load a driver by calling a class.forName( ),that accept driver class
as argument.
• DriverManager.getConnection ( ):This method is used to built a connection between url
and database.
• preparedStatement ( ): This method is used to execute and run a same Statement object
many times, thus it normally uses prepared statement to reduces execution time.
• executeQuery ( ): This method is used to return record set, The return record set is
assigned in a result set. The select statement return you a record set .
• next ( ): This method return you the next element in the series
Transactions
There are times when you do not want one statement to take effect unless another one completes.
For example, when the proprietor of The Coffee Break updates the amount of coffee sold each
week, the proprietor will also want to update the total amount sold to date. However, the amount
sold per week and the total amount sold should be updated at the same time; otherwise, the data
will be inconsistent. The way to be sure that either both actions occur or neither action occurs is
to use a transaction. A transaction is a set of one or more statements that is executed as a unit, so
either all of the statements are executed, or none of the statements is executed.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
77 web:www.weit.in
By default JDBC Connection is in auto commit mode and then every SQL statement is
committed to the database upon its completion. That may be good for simple applications, but
there are three reasons in we want to turn off auto-commit and manage our own transactions :
• To increase performance
• To maintain the integrity of business processes
• To use distributed transactions
Transactions enable us to control when the changes are applied to the database. It treats a single
SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the
whole transaction fails.
1. Disabling Auto-Commit Mode
 When a connection is created, it is in auto-commit mode. This means that each individual
SQL statement is treated as a transaction and is automatically committed right after it is
executed. (To be more precise, the default is for a SQL statement to be committed when
it is completed, not when it is executed. A statement is completed when all of its result
sets and update counts have been retrieved. In almost all cases, however, a statement is
completed, and therefore committed, right after it is executed.)
 The way to allow two or more statements to be grouped into a transaction is to disable the
auto-commit mode. This is demonstrated in the following code, where con is an active
connection:
 con.setAutoCommit(false);
2. Committing Transactions
 After the auto-commit mode is disabled, no SQL statements are committed until you call
the method commit explicitly. All statements executed after the previous call to the
method commit are included in the current transaction and committed together as a unit.
3. Locks
 To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking
access by others to the data that is being accessed by the transaction. (Note that in auto-
commit mode, where each statement is a transaction, locks are held for only one
statement.) After a lock is set, it remains in force until the transaction is committed or
rolled back. For example, a DBMS could lock a row of a table until updates to it have
been committed
4. Setting and Rolling Back to Savepoints
 The method Connection.setSavepoint, sets a Savepoint object within the current
transaction. The Connection.rollback method is overloaded to take a Savepoint argument.
5. Releasing Savepoints
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
78 web:www.weit.in
 The method Connection.releaseSavepoint takes a Savepoint object as a parameter and
removes it from the current transaction.
 After a savepoint has been released, attempting to reference it in a rollback operation
causes a SQLException to be thrown. Any savepoints that have been created in a
transaction are automatically released and become invalid when the transaction is
committed, or when the entire transaction is rolled back. Rolling a transaction back to a
savepoint automatically releases and makes invalid any other savepoints that were
created after the savepoint in question.
6. Rollback
 Calling the method rollback terminates a transaction and returns any values that were
modified to their previous values. If you are trying to execute one or more statements in a
transaction and get a SQLException, call the method rollback to end the transaction and
start the transaction all over again. That is the only way to know what has been
committed and what has not been committed. Catching a SQLException tells you that
something is wrong, but it does not tell you what was or was not committed. Because you
cannot count on the fact that nothing was committed, calling the method rollback is the
only way to be certain.
Using RowSet Objects
A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use
than a result set.
Oracle has defined five RowSet interfaces for some of the more popular uses of a RowSet, and
standard reference are available for these RowSet interfaces. In this tutorial you will learn how to
use these reference implementations.
These versions of the RowSet interface and their implementations have been provided as a
convenience for programmers. Programmers are free write their own versions of the
javax.sql.RowSet interface, to extend the implementations of the five RowSet interfaces, or to write
their own implementations. However, many programmers will probably find that the standard
reference implementations already fit their needs and will use them as is.
Add Scrollability or Updatability
Some DBMSs do not support result sets that can be scrolled (scrollable), and some do not
support result sets that can be updated (updatable). If a driver for that DBMS does not add the
ability to scroll or update result sets, you can use a RowSet object to do it. A RowSet object is
scrollable and updatable by default, so by populating a RowSet object with the contents of a result
set, you can effectively make the result set scrollable and updatable.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
79 web:www.weit.in
Using JdbcRowSet Objects
A JdbcRowSet object is an enhanced ResultSet object. It maintains a connection to its data source,
just as a ResultSet object does. The big difference is that it has a set of properties and a listener
notification mechanism that make it a JavaBeans component.
One of the main uses of a JdbcRowSet object is to make a ResultSet object scrollable and updatable
when it does not otherwise have those capabilities.
Using CachedRowSetObjects
A CachedRowSet object is special in that it can operate without being connected to its data source,
that is, it is a disconnectedRowSet object. It gets its name from the fact that it stores (caches) its
data in memory so that it can operate on its own data rather than on the data stored in a database.
The CachedRowSet interface is the superinterface for all disconnected RowSet objects, so
everything demonstrated here also applies to WebRowSet, JoinRowSet, and FilteredRowSet objects.
Using JoinRowSet Objects
A JoinRowSet implementation lets you create a SQL JOIN between RowSet objects when they are
not connected to a data source. This is important because it saves the overhead of having to
create one or more connections.
Using FilteredRowSet Objects
A FilteredRowSet object lets you cut down the number of rows that are visible in a RowSet object so
that you can work with only the data that is relevant to what you are doing. You decide what
limits you want to set on your data (how you want to "filter" the data) and apply that filter to a
FilteredRowSet object. In other words, the FilteredRowSet object makes visible only the rows of data
that fit within the limits you set. A JdbcRowSet object, which always has a connection to its data
source, can do this filtering with a query to the data source that selects only the columns and
rows you want to see. The query's WHERE clause defines the filtering criteria. A FilteredRowSet
object provides a way for a disconnected RowSet object to do this filtering without having to
execute a query on the data source, thus avoiding having to get a connection to the data source
and sending queries to it.
Using WebRowSet Objects
A WebRowSet object is very special because in addition to offering all of the capabilities of a
CachedRowSet object, it can write itself as an XML document and can also read that XML
document to convert itself back to a WebRowSet object. Because XML is the language through
which disparate enterprises can communicate with each other, it has become the standard for
Web Services communication. As a consequence, a WebRowSet object fills a real need by
enabling Web Services to send and receive data from a database in the form of an XML
document.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
80 web:www.weit.in
UNIT 4
Networking and Socket Programming
Networking
 Computers running on the Internet communicate to each other using either the
Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).
 When you write Java programs that communicate over the network, you are
programming at the application layer.
 Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you
can use the classes in the java.net package.
 These classes provide system-independent network communication.
TCP
 TCP (Transmission Control Protocol) is a connection-based protocol that provides a
reliable flow of data between two computers.
 When two applications want to communicate to each other reliably, they establish a
connection and send data back and forth over that connection.
 This is analogous to making a telephone call. If you want to speak to Aunt Beatrice in
Kentucky, a connection is established when you dial her phone number and she answers.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
81 web:www.weit.in
You send data back and forth over the connection by speaking to one another over the
phone lines.
 TCP provides a point-to-point channel for applications that require reliable
communications.
 The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all
examples of applications that require a reliable communication channel.
UDP
 UDP (User Datagram Protocol) is a protocol that sends independent packets of data,
called datagrams, from one computer to another with no guarantees about arrival. UDP is
not connection-based like TCP.
 Sending datagrams is much like sending a letter through the postal service: The order of
delivery is not important and is not guaranteed, and each message is independent of any
other.
 Many firewalls and routers have been configured not to allow UDP packets. If you're
having trouble connecting to a service outside your firewall, or if clients are having
trouble connecting to your service, ask your system administrator if UDP is permitted.
Ports
 A computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection.
 However, the data may be intended for different applications running on the computer.
So how does the computer know to which application to forward the data?
 Through the use of ports.
 Data transmitted over the Internet is accompanied by addressing information that
identifies the computer and the port for which it is destined.
 The computer is identified by its 32-bit IP address, which IP uses to deliver data to the
right computer on the network.
 Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the
right application.
 In connection-based communication such as TCP, a server application binds a socket to a
specific port number.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
82 web:www.weit.in
In datagram-based communication such as UDP, the datagram packet contains the port number
of its destination and UDP routes the packet to the appropriate application, as illustrated in this
figure:
Working with URL
 URL is the acronym for Uniform Resource Locator.
 It is a reference (an address) to a resource on the Internet.
 You provide URLs to your favorite Web browser so that it can locate files on the Internet
in the same way that you provide addresses on letters so that the post office can locate
your correspondents.
 A URL has two main components:
 Protocol identifier: For the URL http://example.com, the protocol identifier is http.
 Resource name: For the URL http://example.com, the resource name is example.com.
The resource name is the complete address to the resource. The format of the
resource name depends entirely on the protocol used, but for many protocols,
including HTTP, the resource name contains one or more of the following
components:
• Host Name: The name of the machine on which the resource lives.
• Filename: The pathname to the file on the machine.
• Port Number: The port number to which to connect (typically optional).
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
83 web:www.weit.in
• Reference: A reference to a named anchor within a resource that usually identifies a
specific location within a file (typically optional).
What Is a Socket?
 A socket is one endpoint of a two-way communication link between two programs
running on the network.
 A socket is bound to a port number so that the TCP layer can identify the application that
data is destined to be sent.
Normally, a server runs on a specific computer and has a socket that is bound to a specific port
number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running
and the port number on which the server is listening. To make a connection request, the client
tries to rendezvous with the server on the server's machine and port. The client also needs to
identify itself to the server so it binds to a local port number that it will use during this
connection. This is usually assigned by the system.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
84 web:www.weit.in
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a
new socket bound to the same local port and also has its remote endpoint set to the address and
port of the client. It needs a new socket so that it can continue to listen to the original socket for
connection requests while tending to the needs of the connected client.
On the client side, if the connection is accepted, a socket is successfully created and the client
can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Write a TCP uni-direction Socket programming.
//Server file
import java.net.*;
import java.io.*;
class server
{
public static void main(String[] args) throws Exception
{
int portno=1234;
ServerSocket ss= new ServerSocket(portno);
System.out.println("waiting for client to connect...");
Socket s=ss.accept();
System.out.println("Client Connected......");
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str;
while ((str=br.readLine())!=null)
{
System.out.println(str);
}
}
}
//Client file
import java.net.*;
import java.io.*;
class client
{
public static void main(String[] args) throws Exception
{
int portno=1234;
InetAddress ip=InetAddress.getByName(null);
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
85 web:www.weit.in
Socket x=new Socket(ip,portno);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(x.getOutputStream()));
String str;
while ((str=br.readLine())!=null)
{
pw.println(str);
pw.flush();
}
}
}
Output:
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
86 web:www.weit.in
Write a TCP bi-directional Socket programming.
//Client file
import java.net.*;
import java.io.*;
class client1
{
public static void main(String[] args) throws Exception
{
int portno=1234;
InetAddress ip=InetAddress.getByName(null);
Socket x=new Socket(ip,portno);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
BufferedReader br1=new BufferedReader(new
InputStreamReader(x.getInputStream()));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(x.getOutputStream()));
String str=br.readLine();
pw.println(str);
pw.flush();
str=br1.readLine();
System.out.println(str);
}
}
// Server file
import java.net.*;
import java.io.*;
class server1
{
public static void main(String[] args) throws Exception
{
int portno=1234;
ServerSocket ss= new ServerSocket(portno);
System.out.println("waiting for client to connect...");
Socket s=ss.accept();
System.out.println("Client Connected......");
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new
OutputStreamWriter(s.getOutputStream()));
String str=br.readLine();
int num=Integer.parseInt(str);
pw.println("square is " + num*num);
pw.flush();
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
87 web:www.weit.in
}
}
Output:
Write a UDP uni-directional Socket programming.
//unidirectional UDP program client side
import java.io.*;
import java.net.*;
class UIUDPClient
{
public static void main(String[] args)throws Exception
{
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
88 web:www.weit.in
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
InetAddress IPAddress =InetAddress.getByName(null);
byte[] sendData =new byte[1024];
String sentence = inFromUser.readLine();
sendData =sentence.getBytes();
DatagramSocket clientSocket =new DatagramSocket();
DatagramPacket sendPacket = new
DatagramPacket(sendData,sendData.length,IPAddress,9999);
clientSocket.send(sendPacket);
clientSocket.close();
}
}
//unidirectional UDP program server side
import java.io.*;
import java.net.*;
class UIUDPServer
{
public static void main(String[] args)throws Exception
{
DatagramSocket serverSocket =new DatagramSocket(9999);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new
DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String str = new String(receivePacket.getData());
System.out.println("start::"+str);
System.out.println("::end_________________________");
str = str.trim();
int a = Integer.parseInt(str);
System.out.println("square of "+a+" is : "+a*a);
serverSocket.close();
}
}
Output:
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
89 web:www.weit.in
Write a UDP bi-directional Socket programming.
//bidirectional UDP program client side
import java.io.*;
import java.net.*;
class BIUDPClient
{
public static void main(String[] args)throws Exception
{
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
InetAddress IPAddress =InetAddress.getByName(null);
byte[] sendData =new byte[1024];
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
90 web:www.weit.in
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData =sentence.getBytes();
DatagramSocket clientSocket =new DatagramSocket();
DatagramPacket sendPacket = new
DatagramPacket(sendData,sendData.length,IPAddress,9999);
clientSocket.send(sendPacket);
DatagramPacket receivePacket= new
DatagramPacket(receiveData,receiveData.length);
clientSocket.receive(receivePacket);
String square= new String(receivePacket.getData());
System.out.println("From Server::"+square.trim());
clientSocket.close();
}
}
//biidirectional UDP program server side
import java.io.*;
import java.net.*;
class BIUDPServer
{
public static void main(String[] args)throws Exception
{
DatagramSocket serverSocket =new DatagramSocket(9999);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
DatagramPacket receivePacket = new
DatagramPacket(receiveData,receiveData.length);
serverSocket.receive(receivePacket);
String str = new String(receivePacket.getData());
str = str.trim();
int a = Integer.parseInt(str);
int z=a*a;
sendData=(z+"").getBytes();
int port = receivePacket.getPort();
InetAddress IPAddress=receivePacket.getAddress();
DatagramPacket sendPacket = new
DatagramPacket(sendData,sendData.length,IPAddress,port);
serverSocket.send(sendPacket);
serverSocket.close();
}
}
Output:
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
91 web:www.weit.in
Working with URL :
URLConnection
 The abstract class URLConnection is the superclass of all classes that represent a
communications link between the application and a URL.
 Instances of this class can be used both to read from and to write to the resource
referenced by the URL.
In general, creating a connection to a URL is a multistep process:
1) The connection object is created by invoking the openConnection method on URL.
2) The setup parameters and general request properties are manipulated.
3) The actual connection to the remote object is made, using the connect method.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
92 web:www.weit.in
4) The remote object becomes available. The header fields and the contents of the remote
object can be accessed.
Creating a URL
The easiest way to create a URL object is from a String that represents the human-readable form
of the URL address. This is typically the form that another person will use for a URL. In your
Java program, you can use a String containing this text to create a URL object:
URL myURL = new URL("http://example.com/");
Connecting to a URL
After you've successfully created a URL object, you can call the URL object's openConnection
method to get a URLConnection object, or one of its protocol specific subclasses, e.g.
java.net.HttpURLConnection
You can use this URLConnection object to setup parameters and general request properties that
you may need before connecting. Connection to the remote object represented by the URL is
only initiated when the URLConnection.connect method is called. When you do this you are
initializing a communication link between your Java program and the URL over the network. For
example, the following code opens a connection to the site example.com:
try {
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
A new URLConnection object is created every time by calling the openConnection method of
the protocol handler for this URL.
You are not always required to explicitly call the connect method to initiate the connection.
Operations that depend on being connected, like getInputStream, getOutputStream, etc, will
implicitly perform the connection, if necessary.
Example :
import java.net.*;
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
93 web:www.weit.in
import java.io.IOException;
public class getURLConnection
{
public static void main(String args[]) {
URL url; URLConnection ucon; try {
url = new URL("http://www.google.com");
try {
ucon = url.openConnection();
System.out.println(ucon);
}
catch (IOException exp) {
System.err.println(exp);
}
}
catch (MalformedURLException exp) {
System.err.println(exp);
}
}
}
Output:
Reading from a URLConnection
However, rather than getting an input stream directly from the URL, this program explicitly
retrieves a URLConnection object and gets an input stream from the connection. The connection is
opened implicitly by calling getInputStream. Then, like URLReader, this program creates a
BufferedReader on the input stream and reads from it.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
94 web:www.weit.in
WAP to demonstrate reading the content of URL
import java.io.*;
import java.net.*;
class firsturl
{
public static void main(String arg[])throws Exception
{
URL a=new URL("http://www.google.com");
BufferedReader br=new BufferedReader(
new InputStreamReader(a.openStream()));
String str=br.readLine();
if(str!=null)
{
System.out.println(str);
}
}
}
Writing to a URLConnection
Many HTML pages contain forms — text fields and other GUI objects that let you enter data to
send to the server. After you type in the required information and initiate the query by clicking a
button, your Web browser writes the data to the URL over the network. At the other end the
server receives the data, processes it, and then sends you a response, usually in the form of a new
HTML page.
Many of these HTML forms use the HTTP POST METHOD to send data to the server. Thus
writing to a URL is often called posting to a URL. The server recognizes the POST request and
reads the data sent from the client.
For a Java program to interact with a server-side process it simply must be able to write to a
URL, thus providing data to the server. It can do this by following these steps:
1. Create a URL.
2. Retrieve the URLConnection object.
3. Set output capability on the URLConnection.
4. Open a connection to the resource.
5. Get an output stream from the connection.
6. Write to the output stream.
7. Close the output stream.
WAP to demonstrate writing into an URL
import java.io.*;
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
95 web:www.weit.in
import java.net.*;
class secondurl
{
public static void main(String arg[])throws Exception
{
URL a=new URL("http://www.abc.com/first.html");
URLConnection b=a.openConnection();
PrintWriter pw=new PrintWriter(b.getOutputStream());
pw.println("Hello");
}
}
Network Interface
 A network interface is the point of interconnection between a computer and a private or
public network.
 A network interface is generally a network interface card (NIC), but does not have to
have a physical form. Instead, the network interface can be implemented in software.
 For example, the loopback interface (127.0.0.1 for IPv4 and ::1 for IPv6) is not a physical
device but a piece of software simulating a network interface.
 The loopback interface is commonly used in test environments.
Accessing Network interface parameters
 Systems often run with multiple active network connections, such as wired
Ethernet, 802.11 b/g (wireless), and bluetooth.
 Some applications might need to access this information to perform the particular
network activity on a specific connection.
 You can access network parameters about a network interface beyond the name and IP
addresses assigned to it
 You can discover if a network interface is ―up‖ (that is, running) with the isUP() method.
The following methods indicate the network interface type:
 isLoopback() indicates if the network interface is a loopback interface.
 isPointToPoint() indicates if the interface is a point-to-point interface.
 isVirtual() indicates if the interface is a virtual interface.
 The supportsMulticast() method indicates whether the network interface supports
multicasting. The getHardwareAddress() method returns the network interface's physical
hardware address, usually called MAC address, when it is available.
The getMTU() method returns the Maximum Transmission Unit (MTU), which is the
largest packet size.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
96 web:www.weit.in
EXAMPLE
import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;
public class ListNetsEx
{
public static void main(String args[]) throws SocketException
{
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets))
displayInterfaceInformation(netint);
}
static void displayInterfaceInformation(NetworkInterface netint) throws
SocketException
{
out.printf("Display name: %sn", netint.getDisplayName());
out.printf("Name: %sn", netint.getName()); Enumeration<InetAddress>
inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses))
{
out.printf("InetAddress: %sn", inetAddress);
}
out.printf("Up? %sn", netint.isUp());
out.printf("Loopback? %sn", netint.isLoopback());
out.printf("PointToPoint? %sn", netint.isPointToPoint());
out.printf("Supports multicast? %sn", netint.supportsMulticast());
out.printf("Virtual? %sn", netint.isVirtual());
out.printf("Hardware address: %sn",
Arrays.toString(netint.getHardwareAddress()));
out.printf("MTU: %sn", netint.getMTU()); out.printf("n");
}
}
Posting Form Data
Everybody using the Web is at least passingly familiar with POST HTTP request. POST requests
are used to send out things like HTML form data from a Web page to a Web server. A good
example of a POST form is the feedback form at the bottom of the page. The browser sends the
form data as part of the POST request, and the Web server sends back a response (which is
usually in the form of another Web page).
The POST request, however, does not have to be used with an HTML form. It is just another
HTTP request/response protocol. We can use it for whatever nefarious (or legitimate :-) deeds
we care to. For instance, we can use POSTs to a CGI-bin script on a Web server rather than a
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
97 web:www.weit.in
raw socket to a database server. The advantage is you don't have to worry about some users not
being able to use your applet because they happen to sit behind a firewall that refuses to allow
random socket connections to the outside world.
Sending Email
 The Java Mail API provides support for sending and receiving electronic mail messages.
 The API provides a plug-in architecture where vendor‘s implementation for their own
proprietary protocols can be dynamically discovered and used at the run time.
 Sun provides a reference implementation and its supports the following protocols namely
 Internet Mail Access Protocol (IMAP)
 Simple Mail Transfer Protocol (SMTP)
 Post Office Protocol 3(POP 3)
WAP to demonstrate email service.
// File Name SendEmail.java
importjava.util.*;
importjavax.mail.*;
importjavax.mail.internet.*;
importjavax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "abcd@gmail.com";
// Sender's email ID needs to be mentioned
String from = "web@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
98 web:www.weit.in
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingExceptionmex) {
mex.printStackTrace();
}
}
}
Compile and run this program to send a simple email:
$ java SendEmail
Sent message successfully....
If you want to send an email to multiple recipients then following methods
would be used to specify multiple email IDs:
void addRecipients(Message.RecipientType type,
Address[] addresses)
throws MessagingException
Here is the description of the parameters:
 type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC
represents Black Carbon Copy. Example Message.RecipientType.TO
 addresses: This is the array of email ID. You would need to use InternetAddress()
method while specifying email ID
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
99 web:www.weit.in
Cookies
 In www, http protocol is used, this protocol is stateless in nature. i.e the client has to
reintroduce itself on every connection.
 Hence the server stores the client information on the client terminal itself. This
information is stored using COOKIES.
 Cookie is an inbult java class which has an unique identification as one segment and the
client information as the second segment.
 This is the most common way to implement session tracking.
 A cookie cannot grow more than 4Kb in size, and no domain can have more than 20
cookies.
Cookie is an information that contains in a text form is sent to the browser by a servlet which is
saved and resend by the browser to the server for uniquely identifying a client. This feature of
cookie makes it useful for session management. Cookies are send by a servlet to the browser
using addCookie() method of HttpServletResponse interface. Using this method cookies are
send to the browser by adding the fields to HTTP response header. And cookies can be found
from the request by the use of getCookie() method of HttpServletRequset interface. Size and
number of cookie is varied i.e. per web server browser expected to support a 20 cookies, and in
total it supports 300 cookies and the size of per cookie may fix by 4 KB.
In Java EE 6 some new methods are added in Cookie class. Some of these are as follows :
• isHttpOnly() : This method is used to identify for whether the cookie has been noticed
for HttpOnly.
• setHttpOnly() : This method is used to mark or unmark the cookie HttpOnly.
Example:
.html file
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="CookieExample">
Name <input type="text" name= "name"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
100 web:www.weit.in
.java file
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/CookieExample")
public class CookieExample extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
Cookie cookie = new Cookie("Cookie", name);
response.addCookie(cookie);
out.println("Cookie is set for " + name);
cookie.setHttpOnly(true);
boolean bol = cookie.isHttpOnly();
out.println("<br>Cookie is Marked as HttpOnly = " + bol);
cookie.setHttpOnly(false);
boolean bol1 = cookie.isHttpOnly();
out.println("<br>Cookie is Marked as HttpOnly = " + bol1);
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response);
}
}
Serving multiple Clients
When using a Socket class one is establishing a TCP connection to a server on some port, but on
the server the ServerSocket is capable of handling multiple client connections for each accept
request and delegate it to a thread to server the request. But how is it possible for a ServerSocket
class to accept multiple tcp connections on the same port.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
101 web:www.weit.in
Sockets Direct Protocol
 For high performance computing environments, the capacity to move data across a
network quickly and efficiently is a requirement.
 Such networks are typically described as requiring high throughput and low latency.
 High throughput refers to an environment that can deliver a large amount of processing
capacity over a long period of time.
 Low latency refers to the minimal delay between processing input and providing output,
such as you would expect in a real-time application.
Introduced in 1999 by the InfiniBand Trade Association, InfiniBand (IB) was
created to address the need for high performance computing.
RMI
Distributed Object System
Distributed objects are a potentially powerful tool that has only become broadly available for
developers at large in the past few years. The power of distributing objects is not in the fact that a
bunch of objects are scattered across the network. The power lies in that any agent in your
system can directly interact with an object that "lives" on a remote host. Distributed objects, if
they're done right, really give you a tool for opening up your distributed system's resources
across the board.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
102 web:www.weit.in
An object interface specification is used to generate a server implementation of a class of objects,
an interface between the object implementation and the object manager, sometimes called an
object skeleton, and a client interface for the class of objects, sometimes called an object stub.
The skeleton will be used by the server to create new instances of the class of objects and to
route remote method calls to the object implementation. The stub will be used by the client to
route transactions (method invocations, mostly) to the object on the server. On the server side,
the class implementation is passed through a registration service, which registers the new class
with a naming service and an object manager, and then stores the class in the server's storage for
object skeletons.
Overview of RMI Applications
RMI applications often comprise two separate programs, a server and a client. A typical server
program creates some remote objects, makes references to these objects accessible, and waits for
clients to invoke methods on these objects. A typical client program obtains a remote reference
to one or more remote objects on a server and then invokes methods on them. RMI provides the
mechanism by which the server and the client communicate and pass information back and forth.
Such an application is sometimes referred to as a distributed object application.
Distributed object applications need to do the following:
 Locate remote objects. Applications can use various mechanisms to obtain references to
remote objects. For example, an application can register its remote objects with RMI's
simple naming facility, the RMI registry. Alternatively, an application can pass and
return remote object references as part of other remote invocations.
 Communicate with remote objects. Details of communication between remote objects
are handled by RMI. To the programmer, remote communication looks similar to regular
Java method invocations.
 Load class definitions for objects that are passed around. Because RMI enables objects to
be passed back and forth, it provides mechanisms for loading an object's class definitions
as well as for transmitting an object's data.
The following illustration depicts an RMI distributed application that uses the RMI registry to
obtain a reference to a remote object. The server calls the registry to associate (or bind) a name
with a remote object. The client looks up the remote object by its name in the server's registry
and then invokes a method on it. The illustration also shows that the RMI system uses an existing
web server to load class definitions, from server to client and from client to server, for objects
when needed.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
103 web:www.weit.in
The General RMI Architecture
• The server must first bind its name to the registry
• The client lookup the server name in the registry to establish remote references.
The Stub serializing the parameters to skeleton, the skeleton invoking the remote method and
serializing the result back to the stub.
The Stub and Skeleton
RMI Server
skeleton
stub
RMI Client
Registry
bind
lookupreturn call
Local Machine
Remote Machine
Stub
RMI Client RMI Server
skeleton
return
call
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
104 web:www.weit.in
• A client invokes a remote method, the call is first forwarded to stub.
• The stub is responsible for sending the remote call over to the server-side skeleton
• The stub opening a socket to the remote server, marshaling the object parameters and
forwarding the data stream to the skeleton.
• A skeleton contains a method that receives the remote calls, unmarshals the parameters,
and invokes the actual remote object implementation.
RMI Registry Services
The rmiregistry command starts a remote object registry on the specified port on the current
host.
rmiregistry [port]
The rmiregistry command creates and starts a remote object registry on the specified port on the
current host. If port is omitted, the registry is started on port 1099. The rmiregistry command
produces no output and is typically run in the background. For example:
start rmiregistry
A remote object registry is a bootstrap naming service that is used by RMI servers on the same
host to bind remote objects to names. Clients on local and remote hosts can then look up remote
objects and make remote method invocations.
The registry is typically used to locate the first remote object on which an application needs to
invoke methods. That object in turn will provide application-specific support for finding other
objects.
The methods of the java.rmi.registry.LocateRegistry class are used to get a registry
operating on the local host or local host and port.
The URL-based methods of the java.rmi.Naming class operate on a registry and can be used to
look up a remote object on any host, and on the local host: bind a simple (string) name to a
remote object, rebind a new name to a remote object (overriding the old binding), unbind a
remote object, and list the URLs bound in the registry.
Steps for Developing an RMI System
1. Define the remote interface
2. Develop the remote object by implementing the remote interface.
3. Develop the server program.
4. Develop the client program.
5. Compile the Java source files.
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
105 web:www.weit.in
6. Generate the client stubs and server skeletons.
7. Start the RMI registry.
8. Start the remote server objects.
9. Run the client
RMI Program
//Remote Interface File
import java.rmi.*;
public interface testintf extends Remote
{
int add(int x,int y) throws RemoteException;
}
//implementation class
import java.rmi.*;
import java.rmi.server.*;
public class testimpl extends UnicastRemoteObject implements testintf
{
testimpl() throws RemoteException{}
public int add(int x,int y) throws RemoteException
{
return x+y;
}
}
//RMI Server Program
import java.rmi.*;
import java.rmi.server.*;
public class testserver
{
public static void main(String arg[]) throws Exception
{
testimpl ti=new testimpl();
Naming.rebind("addserver",ti);
}
}
//Client application
import java.rmi.*;
public class testclient
{
public static void main(String arg[]) throws Exception
{
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
106 web:www.weit.in
testintf tif=(testintf)Naming.lookup("addserver");
int a=Integer.parseInt(arg[0]);
int b=Integer.parseInt(arg[1]);
System.out.println(tif.add(a,b));
}
}
Output:
ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55
107 web:www.weit.in
Steps to execute RMI program:
SERVER
• javac testint.java
• javac testimp.java
• rmic testimp
• javac testserver.java
• start rmiregistry
• java testserver
CLIENT
• javac testclient.java
• java testclient 5 8

More Related Content

PDF
Sybsc cs sem 3 core java
PDF
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
PDF
tybsc it asp.net full unit 1,2,3,4,5,6 notes
PDF
Sybsc cs sem 3 Web Programming unit 1
PDF
4.129 tybsc it
PDF
PPTX
Java programming(unit 1)
PDF
Core java kvr - satya
Sybsc cs sem 3 core java
Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)
tybsc it asp.net full unit 1,2,3,4,5,6 notes
Sybsc cs sem 3 Web Programming unit 1
4.129 tybsc it
Java programming(unit 1)
Core java kvr - satya

What's hot (18)

PDF
Corejava ratan
PPT
.NET Vs J2EE
PPTX
Java ms harsha
PPT
Inside .net framework
PPT
Attributes & .NET components
PPTX
Training on java niit (sahil gupta 9068557926)
PDF
Advanced programming ch1
PPS
dot NET Framework
PPTX
1.introduction to java
PDF
Visual Studio commands
DOC
.Net assembly
PPTX
Java session2
PDF
Building Enterprise Application with J2EE
PDF
Liit tyit sem 5 enterprise java unit 1 notes 2018
PDF
BCA IPU VB.NET UNIT-I
PPSX
Intoduction to java
PDF
Java basics notes
PDF
(Ebook pdf) java programming language basics
Corejava ratan
.NET Vs J2EE
Java ms harsha
Inside .net framework
Attributes & .NET components
Training on java niit (sahil gupta 9068557926)
Advanced programming ch1
dot NET Framework
1.introduction to java
Visual Studio commands
.Net assembly
Java session2
Building Enterprise Application with J2EE
Liit tyit sem 5 enterprise java unit 1 notes 2018
BCA IPU VB.NET UNIT-I
Intoduction to java
Java basics notes
(Ebook pdf) java programming language basics
Ad

Similar to Tycs advance java sem 5 unit 1,2,3,4 (2017) (20)

PPTX
Chapter 1 swings
PDF
Unit Five.pdf for java Applet and String s
PPTX
swings.pptx
PPT
Swing and AWT in java
PDF
Swingpre 150616004959-lva1-app6892
PPTX
Computer Programming NC III - Java Swing.pptx
PPTX
Java_unit_1_AWTvsSwing.pptxn k , jlnninikkn
PDF
Ebook Pdf O Reilly Java Swing
PPTX
Swing components
PPT
Java Swing
PPTX
Swing !!! y shikhar!!
PDF
Java swing 1
PDF
java presentation on Swings chapter java presentation on Swings
PPTX
Chapter 11.1
PPT
Java lecture
PDF
Swing api
PPT
Windows Programming with Swing
PPT
Chap1 1 1
PPT
Chap1 1.1
PPTX
MODULE 5.pptx gui programming and applets
Chapter 1 swings
Unit Five.pdf for java Applet and String s
swings.pptx
Swing and AWT in java
Swingpre 150616004959-lva1-app6892
Computer Programming NC III - Java Swing.pptx
Java_unit_1_AWTvsSwing.pptxn k , jlnninikkn
Ebook Pdf O Reilly Java Swing
Swing components
Java Swing
Swing !!! y shikhar!!
Java swing 1
java presentation on Swings chapter java presentation on Swings
Chapter 11.1
Java lecture
Swing api
Windows Programming with Swing
Chap1 1 1
Chap1 1.1
MODULE 5.pptx gui programming and applets
Ad

More from WE-IT TUTORIALS (20)

PDF
TYBSC CS 2018 WEB SERVICES NOTES
PDF
TYBSC CS SEM 5 AI NOTES
PPSX
Geographical information system unit 6
PPSX
Geographical information system unit 5
PPSX
Geographical information system unit 4
PPSX
Geographical information system unit 3
PPSX
Geographical information system unit 2
PPSX
Geographical information system unit 1
PDF
Pm unit 1,2,3,4,5,6
PDF
Internet technology unit 5
PDF
Internet technology unit 4
PDF
Internet technology unit 3
PDF
Internet technology unit 2
PDF
Internet technology unit 1
PDF
Internet technology unit 6
PDF
Data warehousing unit 2
PDF
Data warehousing unit 6.1
PDF
Data warehousing unit 5.2
PDF
Data warehousing unit 5.1
PDF
Data warehousing unit 4.2
TYBSC CS 2018 WEB SERVICES NOTES
TYBSC CS SEM 5 AI NOTES
Geographical information system unit 6
Geographical information system unit 5
Geographical information system unit 4
Geographical information system unit 3
Geographical information system unit 2
Geographical information system unit 1
Pm unit 1,2,3,4,5,6
Internet technology unit 5
Internet technology unit 4
Internet technology unit 3
Internet technology unit 2
Internet technology unit 1
Internet technology unit 6
Data warehousing unit 2
Data warehousing unit 6.1
Data warehousing unit 5.2
Data warehousing unit 5.1
Data warehousing unit 4.2

Recently uploaded (20)

PDF
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
PPTX
master seminar digital applications in india
PPTX
Pharma ospi slides which help in ospi learning
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
01-Introduction-to-Information-Management.pdf
PDF
Pre independence Education in Inndia.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Basic Mud Logging Guide for educational purpose
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
Introduction-to-Social-Work-by-Leonora-Serafeca-De-Guzman-Group-2.pdf
master seminar digital applications in india
Pharma ospi slides which help in ospi learning
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Insiders guide to clinical Medicine.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
01-Introduction-to-Information-Management.pdf
Pre independence Education in Inndia.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
TR - Agricultural Crops Production NC III.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
O7-L3 Supply Chain Operations - ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
Basic Mud Logging Guide for educational purpose
Open folder Downloads.pdf yes yes ges yes
The Final Stretch: How to Release a Game and Not Die in the Process.

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.
  • 13. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 11 web:www.weit.in code: import javax.swing.*; import java.awt.*; import java.awt.event.*; public class fourth extends JApplet implements ActionListener,ItemListener { Container cp; JCheckBox c1,c2; JRadioButton r1,r2; JTextField t1; ButtonGroup bg; public void init() { cp=getContentPane(); bg=new ButtonGroup(); cp.setLayout(new FlowLayout()); c1=new JCheckBox("Hockey"); c2=new JCheckBox("cricket"); r1=new JRadioButton("Male"); r2=new JRadioButton("Female"); t1=new JTextField(10); bg.add(r1); bg.add(r2); cp.add(c1); cp.add(c2); cp.add(r1); cp.add(r2); cp.add(t1); r1.addActionListener(this); r2.addActionListener(this); c1.addItemListener(this); c2.addItemListener(this); } public void actionPerformed(ActionEvent ae) { t1.setText(ae.getActionCommand().toString()); }
  • 14. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 12 web:www.weit.in public void itemStateChanged(ItemEvent ie) { String st1= ""; t1.setText(""); if(c1.isSelected()) { st1 = st1 +" "+ (c1.getText()); t1.setText(st1); } if(c2.isSelected()) { st1 = st1 +" "+ (c2.getText()); t1.setText(st1); } } } /*<applet code=fourth height=400 width=400></applet>*/ NOTE  To provide single selection within multiple options, we have to add those appropriate control to a ButtonGroup. WAP to display the following. code:
  • 15. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 13 web:www.weit.in import javax.swing.*; import java.awt.*; import java.awt.event.*; public class fifth extends JApplet implements ActionListener,ItemListener { Container cp; JComboBox c1; JLabel l1,l2,l3; JTextField t1,t2; JButton b1,b2; String str; public void init() { cp=getContentPane(); cp.setLayout(new FlowLayout()); l1=new JLabel("Enter Number"); l2=new JLabel("Select Operation"); l3=new JLabel("Result"); c1=new JComboBox(); c1.addItem("SQUARE"); c1.addItem("CUBE"); t1=new JTextField(20); t2=new JTextField(20); b1=new JButton("Calculate"); b2=new JButton("Clear"); cp.add(l1); cp.add(t1); cp.add(l2); cp.add(c1); cp.add(l3); cp.add(t2); cp.add(b1); cp.add(b2); b1.addActionListener(this); b2.addActionListener(this); c1.addItemListener(this); } public void actionPerformed(ActionEvent ae) { int x=Integer.parseInt(t1.getText()); if(ae.getSource()==b1) { if(c1.getSelectedItem().toString().equals("SQUARE")) {
  • 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;
  • 28. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 26 web:www.weit.in JTextField jt; JPasswordField pf; JFormattedTextField jfd,jfc,jfn,jfp; JTextArea ta; JButton b1; @Override public void init() { cp=getContentPane(); cp.setLayout(new FlowLayout()); jt=new JTextField(15); pf=new JPasswordField(10); pf.setEchoChar('*'); jfd=new JFormattedTextField(new java.util.Date()); jfd.setValue(new Date()); jfd.setColumns(10); jfp=new JFormattedTextField(java.text.NumberFormat.getPercentInstance()); jfp.setValue(new Float("0.67")); jfp.setColumns(5); jfc=new JFormattedTextField(java.text.NumberFormat.getCurrencyInstance()); jfc.setValue(new Float("200")); jfc.setColumns(5); ta=new JTextArea(5,5); b1=new JButton("Click"); cp.add(jt); cp.add(pf); cp.add(jfd); cp.add(jfp); cp.add(jfc); cp.add(ta); cp.add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { ta.append(jt.getText()+"n"+jfd.getValue()+"n"+pf.getSelectedText()); } }
  • 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")
  • 41. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 39 web:www.weit.in code: import java.awt.*; import java.awt.print.*; public class print2D implements Printable { Font sfont=new Font("serif",Font.PLAIN,64); public int print(Graphics g,PageFormat pf,int pageindex) throws PrinterException { if(pageindex>0) { return NO_SUCH_PAGE; } Graphics2D g2=(Graphics2D)g; g2.setFont(sfont); g2.setColor(Color.red); g2.drawString("Hello WE-IT",96,144); return PAGE_EXISTS; } public static void main(String arg[]) { PrinterJob job=PrinterJob.getPrinterJob(); job.setPrintable(new print2D()); if(job.printDialog()) { try { job.print(); } catch(Exception e){} } }
  • 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() {
  • 46. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 44 web:www.weit.in start(); } public void run() { for(int i=11;i<=15;i++) { System.out.println(i); try { Thread.sleep(1000); } catch(Exception e) { } } } } Output: WAP to demonstrate thread by implementing Runnable Interface. class thread2 { public static void main(String arg[]) { mythread mt=new mythread(); for(int i=1;i<=5;i++) {
  • 47. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 45 web:www.weit.in System.out.println(i); try { Thread.sleep(500); } catch(Exception e){} } } } class mythread implements Runnable { Thread t; mythread() { t=new Thread(this); t.start(); } public void run() { for(int i=11;i<=15;i++) { System.out.println(i); try { Thread.sleep(1000); } catch(Exception e){} } } } Output:
  • 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.
  • 54. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 52 web:www.weit.in WAP to demonstrate synchronization. class sync { public static void main(String arg[]) { share s=new share(); mythread mt1=new mythread(s); mythread mt2=new mythread(s); mythread mt3=new mythread(s); } } class mythread extends Thread { share p; mythread(share s) { p=s; start(); } public void run() { p.doword(Thread.currentThread().getName()); } } class share { public synchronized void doword(String str) { for(int i=1;i<=5;i++) { System.out.println(str); try { Thread.sleep(500); } catch(Exception e){} } } } Output:
  • 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 :
  • 75. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 73 web:www.weit.in  TYPE_FORWARD_ONLY : It specifies that a resultset is not scrollable, rows within it can be advanced only in the forward direction.  TYPE_SCROLL_INSENSITIVE : It specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.  TYPE_SCROLL_SENSITIVE : It specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction. The second parameter result Set Concurrency determines whether a resultset is updateable or not and can take one of the two values only :  ResultSet.CONCUR READONLY  ResultSet.CONCUR UPDATABLE Updateable Resultsets Updateable resultsets means the ability to update the contents of specific row(s) in the resultset and propagating these changes to the underlying database. Also the operations of INSERT and DELETE are possible. New rows can be inserted into the underlying table and existing rows can be deleted from both theresultset as well as the underlying table. UPDATE Operation Through a Resultset : The following are the steps involved in creating and using an updateable resultset : 1. To create an updateable resultset, the resultSetConcurrency parameter has to be specified as ResulSet.CONCUR_UPDATABLE while defining the createStatement ( ), preparedStatement ( ), or prepareCall ( ) method on the Connection object. This is shown below: Connection con = null; DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Con=DriverManager.getConnection("jdbc:oracle:thin:@training: 1521 :Oracle"," test", "test"); Statement stmt = conn.create Statement (Resultset. TYPE_SCROLL .SENSITIVE, ResultSet.CONCUR_UPDATEABLE); String sql = “SELECT * FROM EMP”; ResultSet rset = stmt.executeQuery(sql); 2. Use the updateInt() or updateString() etc. methods on the ResultSet object to set the values of the resultset columns. The use of this method is as follows : rset.updateFloat (2, new Value); In above code 2 refers to the second column in the resultset and newValue is a variable that holds a new value to which this column data is to be set to.
  • 76. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 74 web:www.weit.in 3. Use the updateRow ( ) method on the ResultSet object to circulate the changes made to the resultset to the underlying database table and commit them. This has to be done once for each row in the resultset that is changed. This is shown below : rset.updateRow(); JDBC METADATA Metadata means data about data; in other word we can say that it is a short description about detailed data. There are two interfaces that contain the metadata portion of the JDBC. DatabaseMetadata provides information about the database as a whole. It provides methods so that we can discover what a particular database and driver combination can do. ResultSetMetadata is much more specific. It is used to find out about the types and properties of the columns in a ResultSet. This means it can examine what kind of information was returned by a database query or a method of DatabaseMetadata. Generally we use JDBC metadata facilities for Obtaining a list of tables available in the database and Obtaining information about the columns in those tables. ResultSetMetaData An object that can be used to get information about the types and properties of the columns in a ResultSet object. We can get the count of columns and name of columns in the ResulSet using getColumnCount() and getColumnName() method. Example:- Program : three.java import java.sql.*; class three { 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"); ResultSetMetaData rsmd=rs.getMetaData(); int col = rsmd.getColumnCount(); System.out.println("Number of Column : "+ col); System.out.println("Columns Name: "); for (int i = 1; i <= col; i++) {
  • 77. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 75 web:www.weit.in String col_name = rsmd.getColumnName(i); System.out.println(col_name); } st.close(); con.close(); } catch(Exception e){} } } Output of three.java Write a JDBC program to display details of those employees who work in any of the two department ID’s entered by the user through command line argument. Program : four.java import java.sql.*; class four { public static void main(String[] arg) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:mydsn"); PreparedStatement st=con.prepareStatement("select * from student where name=? or name=?"); st.setString(1,arg[0]); st.setString(2,arg[1]); ResultSet rs=st.executeQuery(); while(rs.next()) { System.out.println(rs.getString("rno")+" "+rs.getString("name")); } st.close();
  • 78. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 76 web:www.weit.in con.close(); } catch(Exception e){} } } Output of four.java General Info • Importing a package Java.sql :Network Interface for communicating between front -end application and database. • Inside the try block we load a driver by calling a class.forName( ),that accept driver class as argument. • DriverManager.getConnection ( ):This method is used to built a connection between url and database. • preparedStatement ( ): This method is used to execute and run a same Statement object many times, thus it normally uses prepared statement to reduces execution time. • executeQuery ( ): This method is used to return record set, The return record set is assigned in a result set. The select statement return you a record set . • next ( ): This method return you the next element in the series Transactions There are times when you do not want one statement to take effect unless another one completes. For example, when the proprietor of The Coffee Break updates the amount of coffee sold each week, the proprietor will also want to update the total amount sold to date. However, the amount sold per week and the total amount sold should be updated at the same time; otherwise, the data will be inconsistent. The way to be sure that either both actions occur or neither action occurs is to use a transaction. A transaction is a set of one or more statements that is executed as a unit, so either all of the statements are executed, or none of the statements is executed.
  • 79. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 77 web:www.weit.in By default JDBC Connection is in auto commit mode and then every SQL statement is committed to the database upon its completion. That may be good for simple applications, but there are three reasons in we want to turn off auto-commit and manage our own transactions : • To increase performance • To maintain the integrity of business processes • To use distributed transactions Transactions enable us to control when the changes are applied to the database. It treats a single SQL statement or a group of SQL statements as one logical unit, and if any statement fails, the whole transaction fails. 1. Disabling Auto-Commit Mode  When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for a SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)  The way to allow two or more statements to be grouped into a transaction is to disable the auto-commit mode. This is demonstrated in the following code, where con is an active connection:  con.setAutoCommit(false); 2. Committing Transactions  After the auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit. 3. Locks  To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto- commit mode, where each statement is a transaction, locks are held for only one statement.) After a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed 4. Setting and Rolling Back to Savepoints  The method Connection.setSavepoint, sets a Savepoint object within the current transaction. The Connection.rollback method is overloaded to take a Savepoint argument. 5. Releasing Savepoints
  • 80. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 78 web:www.weit.in  The method Connection.releaseSavepoint takes a Savepoint object as a parameter and removes it from the current transaction.  After a savepoint has been released, attempting to reference it in a rollback operation causes a SQLException to be thrown. Any savepoints that have been created in a transaction are automatically released and become invalid when the transaction is committed, or when the entire transaction is rolled back. Rolling a transaction back to a savepoint automatically releases and makes invalid any other savepoints that were created after the savepoint in question. 6. Rollback  Calling the method rollback terminates a transaction and returns any values that were modified to their previous values. If you are trying to execute one or more statements in a transaction and get a SQLException, call the method rollback to end the transaction and start the transaction all over again. That is the only way to know what has been committed and what has not been committed. Catching a SQLException tells you that something is wrong, but it does not tell you what was or was not committed. Because you cannot count on the fact that nothing was committed, calling the method rollback is the only way to be certain. Using RowSet Objects A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use than a result set. Oracle has defined five RowSet interfaces for some of the more popular uses of a RowSet, and standard reference are available for these RowSet interfaces. In this tutorial you will learn how to use these reference implementations. These versions of the RowSet interface and their implementations have been provided as a convenience for programmers. Programmers are free write their own versions of the javax.sql.RowSet interface, to extend the implementations of the five RowSet interfaces, or to write their own implementations. However, many programmers will probably find that the standard reference implementations already fit their needs and will use them as is. Add Scrollability or Updatability Some DBMSs do not support result sets that can be scrolled (scrollable), and some do not support result sets that can be updated (updatable). If a driver for that DBMS does not add the ability to scroll or update result sets, you can use a RowSet object to do it. A RowSet object is scrollable and updatable by default, so by populating a RowSet object with the contents of a result set, you can effectively make the result set scrollable and updatable.
  • 81. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 79 web:www.weit.in Using JdbcRowSet Objects A JdbcRowSet object is an enhanced ResultSet object. It maintains a connection to its data source, just as a ResultSet object does. The big difference is that it has a set of properties and a listener notification mechanism that make it a JavaBeans component. One of the main uses of a JdbcRowSet object is to make a ResultSet object scrollable and updatable when it does not otherwise have those capabilities. Using CachedRowSetObjects A CachedRowSet object is special in that it can operate without being connected to its data source, that is, it is a disconnectedRowSet object. It gets its name from the fact that it stores (caches) its data in memory so that it can operate on its own data rather than on the data stored in a database. The CachedRowSet interface is the superinterface for all disconnected RowSet objects, so everything demonstrated here also applies to WebRowSet, JoinRowSet, and FilteredRowSet objects. Using JoinRowSet Objects A JoinRowSet implementation lets you create a SQL JOIN between RowSet objects when they are not connected to a data source. This is important because it saves the overhead of having to create one or more connections. Using FilteredRowSet Objects A FilteredRowSet object lets you cut down the number of rows that are visible in a RowSet object so that you can work with only the data that is relevant to what you are doing. You decide what limits you want to set on your data (how you want to "filter" the data) and apply that filter to a FilteredRowSet object. In other words, the FilteredRowSet object makes visible only the rows of data that fit within the limits you set. A JdbcRowSet object, which always has a connection to its data source, can do this filtering with a query to the data source that selects only the columns and rows you want to see. The query's WHERE clause defines the filtering criteria. A FilteredRowSet object provides a way for a disconnected RowSet object to do this filtering without having to execute a query on the data source, thus avoiding having to get a connection to the data source and sending queries to it. Using WebRowSet Objects A WebRowSet object is very special because in addition to offering all of the capabilities of a CachedRowSet object, it can write itself as an XML document and can also read that XML document to convert itself back to a WebRowSet object. Because XML is the language through which disparate enterprises can communicate with each other, it has become the standard for Web Services communication. As a consequence, a WebRowSet object fills a real need by enabling Web Services to send and receive data from a database in the form of an XML document.
  • 82. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 80 web:www.weit.in UNIT 4 Networking and Socket Programming Networking  Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).  When you write Java programs that communicate over the network, you are programming at the application layer.  Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you can use the classes in the java.net package.  These classes provide system-independent network communication. TCP  TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers.  When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection.  This is analogous to making a telephone call. If you want to speak to Aunt Beatrice in Kentucky, a connection is established when you dial her phone number and she answers.
  • 83. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 81 web:www.weit.in You send data back and forth over the connection by speaking to one another over the phone lines.  TCP provides a point-to-point channel for applications that require reliable communications.  The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. UDP  UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.  Sending datagrams is much like sending a letter through the postal service: The order of delivery is not important and is not guaranteed, and each message is independent of any other.  Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble connecting to a service outside your firewall, or if clients are having trouble connecting to your service, ask your system administrator if UDP is permitted. Ports  A computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection.  However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data?  Through the use of ports.  Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined.  The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network.  Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.  In connection-based communication such as TCP, a server application binds a socket to a specific port number.
  • 84. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 82 web:www.weit.in In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure: Working with URL  URL is the acronym for Uniform Resource Locator.  It is a reference (an address) to a resource on the Internet.  You provide URLs to your favorite Web browser so that it can locate files on the Internet in the same way that you provide addresses on letters so that the post office can locate your correspondents.  A URL has two main components:  Protocol identifier: For the URL http://example.com, the protocol identifier is http.  Resource name: For the URL http://example.com, the resource name is example.com. The resource name is the complete address to the resource. The format of the resource name depends entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or more of the following components: • Host Name: The name of the machine on which the resource lives. • Filename: The pathname to the file on the machine. • Port Number: The port number to which to connect (typically optional).
  • 85. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 83 web:www.weit.in • Reference: A reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional). What Is a Socket?  A socket is one endpoint of a two-way communication link between two programs running on the network.  A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.
  • 86. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 84 web:www.weit.in If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client. On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading from their sockets. Write a TCP uni-direction Socket programming. //Server file import java.net.*; import java.io.*; class server { public static void main(String[] args) throws Exception { int portno=1234; ServerSocket ss= new ServerSocket(portno); System.out.println("waiting for client to connect..."); Socket s=ss.accept(); System.out.println("Client Connected......"); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); String str; while ((str=br.readLine())!=null) { System.out.println(str); } } } //Client file import java.net.*; import java.io.*; class client { public static void main(String[] args) throws Exception { int portno=1234; InetAddress ip=InetAddress.getByName(null);
  • 87. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 85 web:www.weit.in Socket x=new Socket(ip,portno); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(new OutputStreamWriter(x.getOutputStream())); String str; while ((str=br.readLine())!=null) { pw.println(str); pw.flush(); } } } Output:
  • 88. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 86 web:www.weit.in Write a TCP bi-directional Socket programming. //Client file import java.net.*; import java.io.*; class client1 { public static void main(String[] args) throws Exception { int portno=1234; InetAddress ip=InetAddress.getByName(null); Socket x=new Socket(ip,portno); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedReader br1=new BufferedReader(new InputStreamReader(x.getInputStream())); PrintWriter pw=new PrintWriter(new OutputStreamWriter(x.getOutputStream())); String str=br.readLine(); pw.println(str); pw.flush(); str=br1.readLine(); System.out.println(str); } } // Server file import java.net.*; import java.io.*; class server1 { public static void main(String[] args) throws Exception { int portno=1234; ServerSocket ss= new ServerSocket(portno); System.out.println("waiting for client to connect..."); Socket s=ss.accept(); System.out.println("Client Connected......"); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream())); String str=br.readLine(); int num=Integer.parseInt(str); pw.println("square is " + num*num); pw.flush();
  • 89. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 87 web:www.weit.in } } Output: Write a UDP uni-directional Socket programming. //unidirectional UDP program client side import java.io.*; import java.net.*; class UIUDPClient { public static void main(String[] args)throws Exception {
  • 90. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 88 web:www.weit.in BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); InetAddress IPAddress =InetAddress.getByName(null); byte[] sendData =new byte[1024]; String sentence = inFromUser.readLine(); sendData =sentence.getBytes(); DatagramSocket clientSocket =new DatagramSocket(); DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,9999); clientSocket.send(sendPacket); clientSocket.close(); } } //unidirectional UDP program server side import java.io.*; import java.net.*; class UIUDPServer { public static void main(String[] args)throws Exception { DatagramSocket serverSocket =new DatagramSocket(9999); byte[] receiveData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length); serverSocket.receive(receivePacket); String str = new String(receivePacket.getData()); System.out.println("start::"+str); System.out.println("::end_________________________"); str = str.trim(); int a = Integer.parseInt(str); System.out.println("square of "+a+" is : "+a*a); serverSocket.close(); } } Output:
  • 91. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 89 web:www.weit.in Write a UDP bi-directional Socket programming. //bidirectional UDP program client side import java.io.*; import java.net.*; class BIUDPClient { public static void main(String[] args)throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); InetAddress IPAddress =InetAddress.getByName(null); byte[] sendData =new byte[1024];
  • 92. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 90 web:www.weit.in byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData =sentence.getBytes(); DatagramSocket clientSocket =new DatagramSocket(); DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,9999); clientSocket.send(sendPacket); DatagramPacket receivePacket= new DatagramPacket(receiveData,receiveData.length); clientSocket.receive(receivePacket); String square= new String(receivePacket.getData()); System.out.println("From Server::"+square.trim()); clientSocket.close(); } } //biidirectional UDP program server side import java.io.*; import java.net.*; class BIUDPServer { public static void main(String[] args)throws Exception { DatagramSocket serverSocket =new DatagramSocket(9999); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length); serverSocket.receive(receivePacket); String str = new String(receivePacket.getData()); str = str.trim(); int a = Integer.parseInt(str); int z=a*a; sendData=(z+"").getBytes(); int port = receivePacket.getPort(); InetAddress IPAddress=receivePacket.getAddress(); DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length,IPAddress,port); serverSocket.send(sendPacket); serverSocket.close(); } } Output:
  • 93. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 91 web:www.weit.in Working with URL : URLConnection  The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL.  Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process: 1) The connection object is created by invoking the openConnection method on URL. 2) The setup parameters and general request properties are manipulated. 3) The actual connection to the remote object is made, using the connect method.
  • 94. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 92 web:www.weit.in 4) The remote object becomes available. The header fields and the contents of the remote object can be accessed. Creating a URL The easiest way to create a URL object is from a String that represents the human-readable form of the URL address. This is typically the form that another person will use for a URL. In your Java program, you can use a String containing this text to create a URL object: URL myURL = new URL("http://example.com/"); Connecting to a URL After you've successfully created a URL object, you can call the URL object's openConnection method to get a URLConnection object, or one of its protocol specific subclasses, e.g. java.net.HttpURLConnection You can use this URLConnection object to setup parameters and general request properties that you may need before connecting. Connection to the remote object represented by the URL is only initiated when the URLConnection.connect method is called. When you do this you are initializing a communication link between your Java program and the URL over the network. For example, the following code opens a connection to the site example.com: try { URL myURL = new URL("http://example.com/"); URLConnection myURLConnection = myURL.openConnection(); myURLConnection.connect(); } catch (MalformedURLException e) { // new URL() failed // ... } catch (IOException e) { // openConnection() failed // ... } A new URLConnection object is created every time by calling the openConnection method of the protocol handler for this URL. You are not always required to explicitly call the connect method to initiate the connection. Operations that depend on being connected, like getInputStream, getOutputStream, etc, will implicitly perform the connection, if necessary. Example : import java.net.*;
  • 95. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 93 web:www.weit.in import java.io.IOException; public class getURLConnection { public static void main(String args[]) { URL url; URLConnection ucon; try { url = new URL("http://www.google.com"); try { ucon = url.openConnection(); System.out.println(ucon); } catch (IOException exp) { System.err.println(exp); } } catch (MalformedURLException exp) { System.err.println(exp); } } } Output: Reading from a URLConnection However, rather than getting an input stream directly from the URL, this program explicitly retrieves a URLConnection object and gets an input stream from the connection. The connection is opened implicitly by calling getInputStream. Then, like URLReader, this program creates a BufferedReader on the input stream and reads from it.
  • 96. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 94 web:www.weit.in WAP to demonstrate reading the content of URL import java.io.*; import java.net.*; class firsturl { public static void main(String arg[])throws Exception { URL a=new URL("http://www.google.com"); BufferedReader br=new BufferedReader( new InputStreamReader(a.openStream())); String str=br.readLine(); if(str!=null) { System.out.println(str); } } } Writing to a URLConnection Many HTML pages contain forms — text fields and other GUI objects that let you enter data to send to the server. After you type in the required information and initiate the query by clicking a button, your Web browser writes the data to the URL over the network. At the other end the server receives the data, processes it, and then sends you a response, usually in the form of a new HTML page. Many of these HTML forms use the HTTP POST METHOD to send data to the server. Thus writing to a URL is often called posting to a URL. The server recognizes the POST request and reads the data sent from the client. For a Java program to interact with a server-side process it simply must be able to write to a URL, thus providing data to the server. It can do this by following these steps: 1. Create a URL. 2. Retrieve the URLConnection object. 3. Set output capability on the URLConnection. 4. Open a connection to the resource. 5. Get an output stream from the connection. 6. Write to the output stream. 7. Close the output stream. WAP to demonstrate writing into an URL import java.io.*;
  • 97. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 95 web:www.weit.in import java.net.*; class secondurl { public static void main(String arg[])throws Exception { URL a=new URL("http://www.abc.com/first.html"); URLConnection b=a.openConnection(); PrintWriter pw=new PrintWriter(b.getOutputStream()); pw.println("Hello"); } } Network Interface  A network interface is the point of interconnection between a computer and a private or public network.  A network interface is generally a network interface card (NIC), but does not have to have a physical form. Instead, the network interface can be implemented in software.  For example, the loopback interface (127.0.0.1 for IPv4 and ::1 for IPv6) is not a physical device but a piece of software simulating a network interface.  The loopback interface is commonly used in test environments. Accessing Network interface parameters  Systems often run with multiple active network connections, such as wired Ethernet, 802.11 b/g (wireless), and bluetooth.  Some applications might need to access this information to perform the particular network activity on a specific connection.  You can access network parameters about a network interface beyond the name and IP addresses assigned to it  You can discover if a network interface is ―up‖ (that is, running) with the isUP() method. The following methods indicate the network interface type:  isLoopback() indicates if the network interface is a loopback interface.  isPointToPoint() indicates if the interface is a point-to-point interface.  isVirtual() indicates if the interface is a virtual interface.  The supportsMulticast() method indicates whether the network interface supports multicasting. The getHardwareAddress() method returns the network interface's physical hardware address, usually called MAC address, when it is available. The getMTU() method returns the Maximum Transmission Unit (MTU), which is the largest packet size.
  • 98. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 96 web:www.weit.in EXAMPLE import java.io.*; import java.net.*; import java.util.*; import static java.lang.System.out; public class ListNetsEx { public static void main(String args[]) throws SocketException { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) displayInterfaceInformation(netint); } static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { out.printf("Display name: %sn", netint.getDisplayName()); out.printf("Name: %sn", netint.getName()); Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { out.printf("InetAddress: %sn", inetAddress); } out.printf("Up? %sn", netint.isUp()); out.printf("Loopback? %sn", netint.isLoopback()); out.printf("PointToPoint? %sn", netint.isPointToPoint()); out.printf("Supports multicast? %sn", netint.supportsMulticast()); out.printf("Virtual? %sn", netint.isVirtual()); out.printf("Hardware address: %sn", Arrays.toString(netint.getHardwareAddress())); out.printf("MTU: %sn", netint.getMTU()); out.printf("n"); } } Posting Form Data Everybody using the Web is at least passingly familiar with POST HTTP request. POST requests are used to send out things like HTML form data from a Web page to a Web server. A good example of a POST form is the feedback form at the bottom of the page. The browser sends the form data as part of the POST request, and the Web server sends back a response (which is usually in the form of another Web page). The POST request, however, does not have to be used with an HTML form. It is just another HTTP request/response protocol. We can use it for whatever nefarious (or legitimate :-) deeds we care to. For instance, we can use POSTs to a CGI-bin script on a Web server rather than a
  • 99. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 97 web:www.weit.in raw socket to a database server. The advantage is you don't have to worry about some users not being able to use your applet because they happen to sit behind a firewall that refuses to allow random socket connections to the outside world. Sending Email  The Java Mail API provides support for sending and receiving electronic mail messages.  The API provides a plug-in architecture where vendor‘s implementation for their own proprietary protocols can be dynamically discovered and used at the run time.  Sun provides a reference implementation and its supports the following protocols namely  Internet Mail Access Protocol (IMAP)  Simple Mail Transfer Protocol (SMTP)  Post Office Protocol 3(POP 3) WAP to demonstrate email service. // File Name SendEmail.java importjava.util.*; importjavax.mail.*; importjavax.mail.internet.*; importjavax.activation.*; public class SendEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try{
  • 100. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 98 web:www.weit.in // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingExceptionmex) { mex.printStackTrace(); } } } Compile and run this program to send a simple email: $ java SendEmail Sent message successfully.... If you want to send an email to multiple recipients then following methods would be used to specify multiple email IDs: void addRecipients(Message.RecipientType type, Address[] addresses) throws MessagingException Here is the description of the parameters:  type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example Message.RecipientType.TO  addresses: This is the array of email ID. You would need to use InternetAddress() method while specifying email ID
  • 101. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 99 web:www.weit.in Cookies  In www, http protocol is used, this protocol is stateless in nature. i.e the client has to reintroduce itself on every connection.  Hence the server stores the client information on the client terminal itself. This information is stored using COOKIES.  Cookie is an inbult java class which has an unique identification as one segment and the client information as the second segment.  This is the most common way to implement session tracking.  A cookie cannot grow more than 4Kb in size, and no domain can have more than 20 cookies. Cookie is an information that contains in a text form is sent to the browser by a servlet which is saved and resend by the browser to the server for uniquely identifying a client. This feature of cookie makes it useful for session management. Cookies are send by a servlet to the browser using addCookie() method of HttpServletResponse interface. Using this method cookies are send to the browser by adding the fields to HTTP response header. And cookies can be found from the request by the use of getCookie() method of HttpServletRequset interface. Size and number of cookie is varied i.e. per web server browser expected to support a 20 cookies, and in total it supports 300 cookies and the size of per cookie may fix by 4 KB. In Java EE 6 some new methods are added in Cookie class. Some of these are as follows : • isHttpOnly() : This method is used to identify for whether the cookie has been noticed for HttpOnly. • setHttpOnly() : This method is used to mark or unmark the cookie HttpOnly. Example: .html file <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="CookieExample"> Name <input type="text" name= "name"/> <input type="submit" value="submit"/> </form> </body> </html>
  • 102. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 100 web:www.weit.in .java file import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/CookieExample") public class CookieExample extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); Cookie cookie = new Cookie("Cookie", name); response.addCookie(cookie); out.println("Cookie is set for " + name); cookie.setHttpOnly(true); boolean bol = cookie.isHttpOnly(); out.println("<br>Cookie is Marked as HttpOnly = " + bol); cookie.setHttpOnly(false); boolean bol1 = cookie.isHttpOnly(); out.println("<br>Cookie is Marked as HttpOnly = " + bol1); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Serving multiple Clients When using a Socket class one is establishing a TCP connection to a server on some port, but on the server the ServerSocket is capable of handling multiple client connections for each accept request and delegate it to a thread to server the request. But how is it possible for a ServerSocket class to accept multiple tcp connections on the same port.
  • 103. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 101 web:www.weit.in Sockets Direct Protocol  For high performance computing environments, the capacity to move data across a network quickly and efficiently is a requirement.  Such networks are typically described as requiring high throughput and low latency.  High throughput refers to an environment that can deliver a large amount of processing capacity over a long period of time.  Low latency refers to the minimal delay between processing input and providing output, such as you would expect in a real-time application. Introduced in 1999 by the InfiniBand Trade Association, InfiniBand (IB) was created to address the need for high performance computing. RMI Distributed Object System Distributed objects are a potentially powerful tool that has only become broadly available for developers at large in the past few years. The power of distributing objects is not in the fact that a bunch of objects are scattered across the network. The power lies in that any agent in your system can directly interact with an object that "lives" on a remote host. Distributed objects, if they're done right, really give you a tool for opening up your distributed system's resources across the board.
  • 104. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 102 web:www.weit.in An object interface specification is used to generate a server implementation of a class of objects, an interface between the object implementation and the object manager, sometimes called an object skeleton, and a client interface for the class of objects, sometimes called an object stub. The skeleton will be used by the server to create new instances of the class of objects and to route remote method calls to the object implementation. The stub will be used by the client to route transactions (method invocations, mostly) to the object on the server. On the server side, the class implementation is passed through a registration service, which registers the new class with a naming service and an object manager, and then stores the class in the server's storage for object skeletons. Overview of RMI Applications RMI applications often comprise two separate programs, a server and a client. A typical server program creates some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on these objects. A typical client program obtains a remote reference to one or more remote objects on a server and then invokes methods on them. RMI provides the mechanism by which the server and the client communicate and pass information back and forth. Such an application is sometimes referred to as a distributed object application. Distributed object applications need to do the following:  Locate remote objects. Applications can use various mechanisms to obtain references to remote objects. For example, an application can register its remote objects with RMI's simple naming facility, the RMI registry. Alternatively, an application can pass and return remote object references as part of other remote invocations.  Communicate with remote objects. Details of communication between remote objects are handled by RMI. To the programmer, remote communication looks similar to regular Java method invocations.  Load class definitions for objects that are passed around. Because RMI enables objects to be passed back and forth, it provides mechanisms for loading an object's class definitions as well as for transmitting an object's data. The following illustration depicts an RMI distributed application that uses the RMI registry to obtain a reference to a remote object. The server calls the registry to associate (or bind) a name with a remote object. The client looks up the remote object by its name in the server's registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing web server to load class definitions, from server to client and from client to server, for objects when needed.
  • 105. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 103 web:www.weit.in The General RMI Architecture • The server must first bind its name to the registry • The client lookup the server name in the registry to establish remote references. The Stub serializing the parameters to skeleton, the skeleton invoking the remote method and serializing the result back to the stub. The Stub and Skeleton RMI Server skeleton stub RMI Client Registry bind lookupreturn call Local Machine Remote Machine Stub RMI Client RMI Server skeleton return call
  • 106. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 104 web:www.weit.in • A client invokes a remote method, the call is first forwarded to stub. • The stub is responsible for sending the remote call over to the server-side skeleton • The stub opening a socket to the remote server, marshaling the object parameters and forwarding the data stream to the skeleton. • A skeleton contains a method that receives the remote calls, unmarshals the parameters, and invokes the actual remote object implementation. RMI Registry Services The rmiregistry command starts a remote object registry on the specified port on the current host. rmiregistry [port] The rmiregistry command creates and starts a remote object registry on the specified port on the current host. If port is omitted, the registry is started on port 1099. The rmiregistry command produces no output and is typically run in the background. For example: start rmiregistry A remote object registry is a bootstrap naming service that is used by RMI servers on the same host to bind remote objects to names. Clients on local and remote hosts can then look up remote objects and make remote method invocations. The registry is typically used to locate the first remote object on which an application needs to invoke methods. That object in turn will provide application-specific support for finding other objects. The methods of the java.rmi.registry.LocateRegistry class are used to get a registry operating on the local host or local host and port. The URL-based methods of the java.rmi.Naming class operate on a registry and can be used to look up a remote object on any host, and on the local host: bind a simple (string) name to a remote object, rebind a new name to a remote object (overriding the old binding), unbind a remote object, and list the URLs bound in the registry. Steps for Developing an RMI System 1. Define the remote interface 2. Develop the remote object by implementing the remote interface. 3. Develop the server program. 4. Develop the client program. 5. Compile the Java source files.
  • 107. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 105 web:www.weit.in 6. Generate the client stubs and server skeletons. 7. Start the RMI registry. 8. Start the remote server objects. 9. Run the client RMI Program //Remote Interface File import java.rmi.*; public interface testintf extends Remote { int add(int x,int y) throws RemoteException; } //implementation class import java.rmi.*; import java.rmi.server.*; public class testimpl extends UnicastRemoteObject implements testintf { testimpl() throws RemoteException{} public int add(int x,int y) throws RemoteException { return x+y; } } //RMI Server Program import java.rmi.*; import java.rmi.server.*; public class testserver { public static void main(String arg[]) throws Exception { testimpl ti=new testimpl(); Naming.rebind("addserver",ti); } } //Client application import java.rmi.*; public class testclient { public static void main(String arg[]) throws Exception {
  • 108. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 106 web:www.weit.in testintf tif=(testintf)Naming.lookup("addserver"); int a=Integer.parseInt(arg[0]); int b=Integer.parseInt(arg[1]); System.out.println(tif.add(a,b)); } } Output:
  • 109. ADDRESS:302 PARANJPE UDYOG BHAVAN,OPP SHIVSAGAR RESTAURANT,THANE [W].PH 8097071144/55 107 web:www.weit.in Steps to execute RMI program: SERVER • javac testint.java • javac testimp.java • rmic testimp • javac testserver.java • start rmiregistry • java testserver CLIENT • javac testclient.java • java testclient 5 8