Lecture Notes Java 2009 10 STUDENT
Lecture Notes Java 2009 10 STUDENT
• The Swing Components - Include everything from buttons to split panes to tables.
• Pluggable Look and Feel Support - Gives any program that uses Swing
components a choice of looks and feels. For example, the same program can use
either the JavaTM look and feel or the Windows look and feel. We expect many
more look-and-feel packages -- including some that use sound instead of a visual
"look" -- to become available from various sources.
• Accessibility API - Enables assistive technologies such as screen readers and
Braille displays to get information from the user interface.
• Java 2DTM API - Enables developers to easily incorporate high-quality 2D
graphics, text, and images in applications and in applets.
• Drag and Drop Support - Provides the ability to drag and drop between a Java
application and a native application.
The biggest difference between the AWT components and Swing components is that the
Swing components are implemented with absolutely no native code. Since Swing
components aren't restricted to the least common denominator -- the features that are
present on every platform -- they can have more functionality than AWT components.
Because the Swing components have no native code, they can be be shipped as an add-on
to JDK 1.1, in addition to being part of the Java 2 Platform.
Swing lets you specify which look and feel your program's GUI uses. By contrast, AWT
components always have the look and feel of the native platform.
-1-
Siddhesh Kadam TyBsc Advance Java
import javax.swing.*;
import java.awt.*;
public Login()
{
Container con=getContentPane();
txtName=new JTextField();
txtPass =new JTextField();
con.add(lblName); con.add(txtName);
con.add(lblPass); con.add(txtPass);
con.add(cmdOk); con.add(cmdCancel);
}//constructor
-2-
Siddhesh Kadam TyBsc Advance Java
Most Swing programs also need to import the two main AWT packages:
import java.awt.*;
import java.awt.event.*;
Every program that presents a Swing GUI contains at least one top-level Swing container.
For most programs, the top-level Swing containers are instances of JFrame, JDialog, or
JApplet. Each JFrame object implements a single main window, and each JDialog
implements a secondary window. Each JApplet object implements an applet's display
area within a browser window. A top-level Swing container provides the support that
Swing components need to perform their painting and event handling.
Every Container has a default layout manger that places the components inside the
container according to the available size of the conent pane. More on this later.
In the above example, first instances are created so that they can be accessed from
anywhere in the program and then the objects are created inside the constructor.
In swing we cannot add a component directly to the heavy weight, we need to get the
object of the content pane and add all the components to the content pane. We use the
method getContentPane() of the heavy container to get a Container object. We then add
all the components to the Container object. More on this in the next section.
IF the heavy weight continer is JFrame the we need to write the main(). The main() will
include the object of the class. Two important properties we need to set is the size and
visibility. The methods used are setSize() and setVisible().
-3-
Siddhesh Kadam TyBsc Advance Java
Each event is represented by an object that gives information about the event and
identifies the event source. Event sources are typically components, but other
kinds of objects can also be event sources. Each event source can have multiple
listeners registered on it. Conversely, a single listener can register with multiple
event sources.
-4-
Siddhesh Kadam TyBsc Advance Java
• Painting - Painting means drawing the component on-screen. Although it's easy to
customize a component's painting, most programs don't do anything more
complicated than customizing a component's border.
• Threads and Swing - If you do something to a visible component that might
depend on or affect its state, then you need to do it from the event-dispatching
thread. This isn't an issue for many simple programs, which generally refer to
components only in event-handling code.
• More Swing Features and Concepts - Swing offers many features, many of which
rely on support provided by the JComponent class. Some of the interesting
features include support for icons, actions, Pluggable Look & Feel technology,
assistive technologies, and separate models.
Constructors :
Methods :
-5-
Siddhesh Kadam TyBsc Advance Java
JDialog
The JDialog is the main class for creating a dialog window. You can use this class to
create a custom dialog, or invoke the many class methods in JOptionPane to create a
variety of standard dialogs. Every dialog is dependent on a frame. When that frame is
destroyed, so are its dependent dialogs. When the frame is iconified, its dependent
dialogs disappear from the screen. When the frame is deiconified, its dependent dialogs
return to the screen.
A dialog can be modal. When a modal dialog is visible, it blocks user input to all other
windows in the program. The dialogs that JOptionPane provides are modal. To create a
non-modal dialog, you must use the JDialog class directly. To create simple, standard
dialogs, you use the JOptionPane class. The ProgressMonitor class can put up a dialog
that shows the progress of an operation. Two other classes, JColorChooser and
JFileChooser, also supply standard dialogs.
Constructors :
JDialog(Frame owner) Creates a non-modal dialog without a title with the specifed
Frame as its owner.
JDialog(Frame owner, Creates a modal or non-modal dialog without a title and with the
boolean modal) specified owner Frame.
JDialog(Frame owner, Creates a non-modal dialog with the specified title and with the
String title) specified owner frame.
JDialog(Frame owner, Creates a modal or non-modal dialog with the specified title and
-6-
Siddhesh Kadam TyBsc Advance Java
JApplet
JApplet is an extended version of java.applet.Applet that adds support for the JFC/Swing
component architecture. The JApplet class is slightly incompatible with
java.applet.Applet. JApplet contains a JRootPane as it's only child. The contentPane
should be the parent of any children of the JApplet.
To add the child to the JApplet's contentPane we use the getContentPane() method and
add the components to the contentPane. The same is true for setting LayoutManagers,
removing components, listing children, etc. All these methods should normally be sent to
the contentPane() instead of the JApplet itself. The contentPane() will always be non-
null. Attempting to set it to null will cause the JApplet to throw an exception. The default
contentPane() will have a BorderLayout manager set on it.
JApplet adds two major features to the functionality that it inherits from
java.applet.Applet. First, Swing applets provide support for assistive technologies.
Second, because JApplet is a top-level Swing container, each Swing applet has a root
pane. The most noticeable results of the root pane's presence are support for adding a
menu bar and the need to use a content pane.
Constructors :
JApplet()
Creates a swing applet instance.
Methods:
1 Container getContentPane()
Returns the contentPane object for this applet.
2 void setJMenuBar(JMenuBar menuBar)
Sets the menubar for this applet.
3 void setLayout(LayoutManager manager)
By default the layout of this component may not be set, the layout of its
contentPane should be set instead.
4 void update(Graphics g)
Just calls paint(g).
-7-
Siddhesh Kadam TyBsc Advance Java
Example 2.1: Define a class that produces an applet, which performs a simple
animation of drawing a rectangle on double clicking anywhere on the screen. At the
same time the previous rectangle should get deleted.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.*;
//<applet code=RectDemo.class height=300 width=300></applet>
public class RectDemo extends Applet
{
int mx,my;
public void init()
{
RectDemoListener rdl=new RectDemoListener(this);
addMouseListener(rdl);
}//init
public void paint(Graphics g)
{
g.drawRect(mx,my,50,100);
}
}//class
-8-
Siddhesh Kadam TyBsc Advance Java
Example 2.2: Create an applet that displays the current position of the mouse in its
status bar. e. g. [20,30]. As mouse is moved these numbers go on changing.
import javax.swing.JApplet;
import java.awt.*;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseStatus;
//<applet code=MouseStatus.class height=300 width=300></applet>
public class MouseStatus extends JApplet
{
public void init()
{
MouseStatusListener msl=new MouseStatusListener(this);
addMouseMotionListener(msl);
}//init
}//class
-9-
Siddhesh Kadam TyBsc Advance Java
Example 2.3: Create an applet that displays a small figure on the screen. When
mouse is moved, determine whether the mouse is close to the position occupied by
the figure. If so redraw the figure at a new position further away from the mouse. If
the figure strikes a wall of the screen, cause it to bounce off the wall.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<Applet code=CatchRect.class height=500 width=500></applet>
public class CatchRect extends Applet
{
int x1,y1,x2,y2,x3,y3,x4,y4,x5,y5;
int mx,my;
public void init()
{
CatchRectListener crl=new CatchRectListener(this);
addMouseMotionListener(crl);
x1=50; y1=75; x2=80; y2=100;
}
public void paint(Graphics g)
{
x3=x1-50; y3=y1-50; x4=x2+50; y4=y2+50;
g.drawRect(x5,y5,x2,y2);
}
}//class
class CatchRectListener implements MouseMotionListener
{
CatchRect c;
public CatchRectListener(CatchRect c)
{
this.c=c;
}
public void mouseMoved(MouseEvent e)
{
int newx,newy;
c.mx=e.getX();
c.my=e.getY();
if (c.mx<c.x4 || c.my<c.y4 || c.mx>c.x3 || c.my>c.y3)
{
c.x5=(int)(Math.random()*500);
c.y5=(int)(Math.random()*500);
}
c.repaint();
}
public void mouseDragged(MouseEvent e){}
}//class
- 10 -
Siddhesh Kadam TyBsc Advance Java
Example 2.4 : Write an applet that draws a dot at random location in its display
area every 200 milliseconds. Any dots that already exist are not erased. Therefore,
dots accumulate as the applet executes.
import javax.swing.*;
import java.awt.event.*;
import java.lang.*;
//<applet code=Dot.class height=600 width=600></applet>
public class Dot extends JApplet implements Runnable
{
Graphics g;
int x,y,r,gr,b;
Thread t= new Thread(this);
- 11 -
Siddhesh Kadam TyBsc Advance Java
Example 2.5: Define a class that enables the drawing of freehand lines on a screen
through mouse clicking and dragging. Use anonymous inner classes to implement
event listeners. The drawing should be cleared when a key is pressed and the line
color should be selectable. Define a test class to demonstrate the program.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.applet.JApplet;
//<applet code="FreeHand.class" width=500 height=500 > </applet>
public class FreeHand extends JApplet
{
int lastx,lasty,newx,newy;
JButton b1=new JButton("Color Chooser");
JColorChooser c1= new JColorChooser();
Graphics g;
Color ss;
public void init()
{
FreeHandListener fhl=new FreeHandListener(this);
g=getGraphics();
JPanel jp=(JPanel)getContentPane();
jp.setLayout(new FlowLayout());
b1.addActionListener(fhl);
jp.add(b1);
addMouseListener(fhl);
addMouseMotionListener(fhl);
addKeyListener(fhl);
}
}// Class FH
class FreeHandListener implements
ActionListener,MouseMotionListener,MouseListener,KeyListener
{
FreeHand fh;
public FreeHandListener(FreeHand fh)
{
this.fh=fh;
}
public void actionPerformed(ActionEvent e)
{
JDialog jd=JColorChooser.createDialog(fh,"Choose
Color",true,fh.c1,new SetColor(fh),null);
jd.setVisible(true);
}
public class SetColor implements ActionListener
{
FreeHand fh;
- 12 -
Siddhesh Kadam TyBsc Advance Java
- 13 -
Siddhesh Kadam TyBsc Advance Java
JWindow
A JWindow is a container that can be displayed anywhere on the user's desktop. It does
not have the title bar, window-management buttons, or other trimmings associated with a
JFrame, but it is still a "first-class citizen" of the user's desktop, and can exist anywhere
on it. The JWindow component contains a JRootPane as its only child. The contentPane
should be the parent of any children of the JWindow. From the older java.awt.Window
object you would normally do something like this:
window.add(child);
However, using JWindow you would code:
window.getContentPane().add(child);
The same is true of setting LayoutManagers, removing components, listing children, etc.
All these methods should normally be sent to the contentPane instead of the JWindow
itself. The contentPane will always be non-null. Attempting to set it to null will cause the
JWindow to throw an exception. The default contentPane will have a BorderLayout
manager set on it.
Constructors:
JWindow()
Creates a window with no specified owner.
JWindow(Frame owner)
Creates a window with the specified owner frame.
JWindow(Window owner)
Creates a window with the specified owner window.
Methods :
1 Conatiner getContentPane()
Returns the contentPane object for this applet.
2 void setLayout(LayoutManager manager)
By default the layout of this component may not be set, the layout of its
contentPane should be set instead.
3 void update(Graphics g)
Just calls paint(g).
4 void windowInit()
Called by the constructors to init the JWindow properly.
- 14 -
Siddhesh Kadam TyBsc Advance Java
hierarchy. Each containment hierarchy has a top-level container as its root. Each top-level
container has a content pane that, generally speaking, contains the visible components in
that top-level container's GUI. You can optionally add a menu bar to a top-level
container. The menu bar is positioned within the top-level container, but outside the
content pane.
Each program that uses Swing components has at least one top-level container. This top-
level container is the root of a containment hierarchy -- the hierarchy that contains all of
the Swing components that appear inside the top-level container. As a rule, a standalone
application with a Swing-based GUI has at least one containment hierarchy with a
JFrame as its root.
Here's the code that is used to get a frame's content pane and add the yellow label to it:
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
As the code shows, you find the content pane of a top-level container by calling the
getContentPane method. The default content pane is a simple intermediate container that
inherits from JComponent, and that uses a BorderLayout as its layout manager. It's easy
to customize the content pane -- setting the layout manager or adding a border, for
example. The getContentPane method returns a Container object, not a JComponent
object.
- 15 -
Siddhesh Kadam TyBsc Advance Java
All top-level containers can, in theory, have a menu bar. In practice, however, menu bars
usually appear only in frames and perhaps in applets. To add a menu bar to a frame or
applet, you create a JMenuBar object, populate it with menus, and then call setJMenuBar.
To adds a menu bar to its frame use this code:
frame.setJMenuBar(MenuBar_Name);
Each top-level container relies on a reclusive intermediate container called the root pane.
The root pane manages the content pane and the menu bar, along with a couple of other
containers. If you need to intercept mouse clicks or paint over multiple components, you
should get acquainted with root panes.
We've already discussed about the content pane and the optional menu bar. The two other
components that a root pane adds are a layered pane and a glass pane. The layered pane
directly contains the menu bar and content pane, and enables Z-ordering of other
components you might add. The glass pane is often used to intercept input events
occuring over the top-level container, and can also be used to paint over multiple
components.
JRootPane's layeredPane
JRootPane's glassPane
The glassPane sits on top of all other components in the JRootPane. This positioning
makes it possible to intercept mouse events, which is useful for dragging one component
across another. This positioning is also useful for drawing.
- 16 -
Siddhesh Kadam TyBsc Advance Java
When you add components to a panel, you use the add method. Exactly which arguments
you specify to the add method depend on which layout manager the panel uses. When the
layout manager is FlowLayout, BoxLayout, GridLayout, or GridBagLayout, you'll
typically use the one-argument add method, like this:
aFlowPanel.add(aComponent);
aFlowPanel.add(anotherComponent);
When the layout manager is BorderLayout, you need to provide a second argument
specifying the added component's position within the panel. For example:
aBorderPanel.add(aComponent, BorderLayout.CENTER);
aBorderPanel.add(anotherComponent, BorderLayout.SOUTH);
Constructors :
Constructor Purpose
JPanel() Create a panel. The LayoutManager parameter provides a
JPanel(LayoutManager) layout manager for the new panel. By default, a panel uses a
FlowLayout to lay out its components.
Methods :
Method Purpose
void add(Component) Add the specified component to the panel. When present, the
void add(Component, int) int parameter is the index of the component within the
void add(Component, container. By default, the first component added is at index
Object) 0, the second is at index 1, and so on. The Object parameter
void add(Component, is layout manager dependent and typically provides
Object, int) information to the layout manager regarding positioning and
other layout constraints for the added component.
void remove(Component)
void remove(int) Remove the specified component(s).
void removeAll()
- 17 -
Siddhesh Kadam TyBsc Advance Java
void Set or get the layout manager for this panel. The layout
setLayout(LayoutManager) manager is responsible for positioning the panel's
LayoutManager components within the panel's bounds according to some
getLayout() philosophy.
import javax.swing.JApplet;
import java.awt.Container;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Color;
import java.awt.Canvas;
import java.awt.event.*;
//<applet code=MyColoredCanvas.class height=500 width=500></applet>
Container con=getContentPane();
con.setLayout(new GridBagLayout());
gbc.gridx=2;
gbc.gridy=2;
con.add(cc,gbc);
}
}
- 18 -
Siddhesh Kadam TyBsc Advance Java
JSrollPane
JScrollPane provides a scrollable view of a component. A JScrollPane manages a
viewport, optional vertical and horizontal scroll bars, and optional row and column
heading viewports.
To add a border around the main viewport, you can use setViewportBorder. A common
operation to want to do is to set the background color that will be used if the main
viewport view is smaller than the viewport. This can be accomplished by setting the
background color of the viewport, via
scrollPane.getViewport().setBackground().
Constructors :
Constructor Purpose
JScrollPane() Create a scroll pane. The Component parameter, when
JScrollPane(Component) present, sets the scroll pane's client. The two int parameters,
JScrollPane(int, int) when present, set the vertical and horizontal scroll bar
JScrollPane(Component, policies (respectively).
int, int)
- 19 -
Siddhesh Kadam TyBsc Advance Java
Methods:
Method Purpose
void setVerticalScrollBarPolicy(int) Set or get the vertical scroll policy.
int getVerticalScrollBarPolicy() ScrollPaneConstants defines three values for
SAME FOR HORIZONTAL specifying this policy:
VERTICAL_SCROLLBAR_AS_NEEDED (the
default), VERTICAL_SCROLLBAR_ALWAYS,
and VERTICAL_SCROLLBAR_NEVER.
void setViewportBorder(Border) Set or get the border around the viewport.
Border getViewportBorder()
void
setColumnHeaderView(Component)
Set the column or row header for the scroll pane.
void
setRowHeaderView(Component)
void setCorner(Component, int) Set or get the corner specified. The int parameter
Component getCorner(int) specifies which corner and must be one of the
following constants defined in
ScrollPaneConstants: UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER, and
LOWER_RIGHT_CORNER.
Split Panes
A JSplitPane displays two components, either side by side or one on top of the other. By
dragging the divider that appears between the components, the user can specify how
much of the split pane's total area goes to each component. You can divide screen space
among three or more components by putting split panes inside of split panes, as described
in Nesting Split Panes.
Instead of adding the components of interest directly to a split pane, you often put each
component into a scroll pane. You then put the scroll panes into the split pane. This
allows the user to view any part of a component of interest, without requiring the
component to take up a lot of screen space or adapt to displaying itself in varying
amounts of screen space.
When the user is resizing the Components the minimum size of the Components is used
to determine the maximum/minimum position the Components can be set to. If the
minimum size of the two components is greater than the size of the split pane the divider
will not allow you to resize it. To alter the minimum size of a JComponent, see
JComponent.setMinimumSize(java.awt.Dimension).
- 20 -
Siddhesh Kadam TyBsc Advance Java
Constructors:
Constructor Purpose
JSplitPane() Create a split pane. When present, the int
JSplitPane(int) parameter indicates the split pane's orientation,
JSplitPane(int, boolean) either HORIZONTAL_SPLIT (the default) or
JSplitPane(int, Component, VERTICAL_SPLIT. The boolean parameter,
Component) when present, sets whether the components
JSplitPane(int, boolean, continually repaint as the user drags the split
Component, Component) pane. If left unspecified, this option (called
continuous layout) is turned off. The
Component parameters set the initial left and
right, or top and bottom components,
respectively.
Methods:
Method Purpose
void setOrientation(int) Set or get the split pane's orientation. Use either
int getOrientation() HORIZONTAL_SPLIT or VERTICAL_SPLIT
defined in JSplitPane. If left unspecified, the split
pane will be horizontally split.
void setDividerSize(int) Set or get the size of the divider in pixels.
int getDividerSize()
void Set or get whether the split pane's components are
setContinuousLayout(boolean) continually layed out and painted while the user
boolean getContinuousLayout() is dragging the divider. By default, continuous
layout is turned off.
void remove(Component) Remove the indicated component(s) from the
void removeAll() split pane.
void add(Component) Add the component to the split pane. You can add
only two components to a split pane. The first
component added is the top/left component. The
second component added is the bottom/right
component. Attempt to add more components
result in an exception.
Tabbed Panes
A component that lets the user switch between a group of components by clicking on a
tab with a given title and/or icon. Tabs/components are added to a TabbedPane object by
using the addTab and insertTab methods. A tab is represented by an index corresponding
- 21 -
Siddhesh Kadam TyBsc Advance Java
to the position it was added in, where the first tab has an index equal to 0 and the last tab
has an index equal to the tab count minus 1.
The TabbedPane uses a SingleSelectionModel to represent the set of tab indices and the
currently selected index. If the tab count is greater than 0, then there will always be a
selected index, which by default will be initialized to the first tab. If the tab count is 0,
then the selected index will be -1.
Constructors:
Constructor Purpose
JTabbedPane() Creates a tabbed pane. The first optional argument
JTabbedPane(int tabPlacement) specifies where the tabs should appear. By default,
JTabbedPane(int tabPlacement, the tabs appear at the top of the tabbed pane.You can
int tabLayoutPolicy) specify these positions TOP, BOTTOM, LEFT,
RIGHT. The second optional argument specifies the
tab layout policy.
Methods:
Method Purpose
JTabbedPane() Create a tabbed pane. The optional argument
JTabbedPane(int) specifies where the tabs should appear. By default,
the tabs appear at the top of the tabbed pane. You
can specify these positions (defined in the
SwingConstants interface, which JTabbedPane
implements): TOP, BOTTOM, LEFT, RIGHT.
addTab(String, Icon, Component, Add a new tab to the tabbed pane. The first
String) argument specifies the text on the tab. The
addTab(String, Icon, Component) optional icon argument specifies the tab's icon.
addTab(String, Component) The component argument specifies the component
that the tabbed pane should show when the tab is
selected. The fourth argument, if present, specifies
the tool tip text for the tab.
insertTab(String, Icon, Component, Insert a tab at the specified index, where the first
String, int) tab is at index 0. The arguments are the same as
for addTab.
void setSelectedIndex(int) Select the tab that has the specified component or
void index. Selecting a tab has the effect of displaying
setSelectedComponent(Component) its associated component.
void setEnabledAt(int, boolean) Set or get the enabled state of the tab at the
boolean isEnabledAt(int) specified index.
- 22 -
Siddhesh Kadam TyBsc Advance Java
Example 4:
import javax.swing.*;
//<applet code="TabbedPaneDemo.class" height=500 width=500></applet>
public class TabbedPaneDemo extends JApplet {
public CitiesPanel() {
add(new JButton("Mumbai"));
add(new JButton("Delhi"));
add(new JButton("Banglore"));
add(new JButton("Chennai"));
}
}
public ColorPanel() {
add(new JCheckBox("Red"));
add(new JCheckBox("Yellow"));
add(new JCheckBox("Green"));
add(new JCheckBox("Blue"));
}
}
public FlavourPanel() {
String item[]={"Vanila","Stroberry","Chocolet"};
JComboBox jcb=new JComboBox(item);
add(jcb);
}
- 23 -
Siddhesh Kadam TyBsc Advance Java
Internal Frames
A lightweight object that provides many of the features of a native frame, including
dragging, closing, becoming an icon, resizing, title display, and support for a menu bar.
Constructors:
Constructor Summary
JInternalFrame()
Creates a non-resizable, non-closable, non-maximizable, non-iconifiable
JInternalFrame with no title.
JInternalFrame(String title)
Creates a non-resizable, non-closable, non-maximizable, non-iconifiable
JInternalFrame with the specified title.
JInternalFrame(String title, boolean resizable)
Creates a non-closable, non-maximizable, non-iconifiable JInternalFrame with the
specified title and resizability.
JInternalFrame(String title, boolean resizable, boolean closable)
Creates a non-maximizable, non-iconifiable JInternalFrame with the specified title,
resizability, and closability.
Methods:
Method Purpose
Make the internal frame visible (if true) or invisible (if false).
void
You should invoke setVisible(true) on each JInternalFrame
setVisible(boolean)
before adding it to its container. (Inherited from Component).
void pack() Size the internal frame so that its components are at their
- 24 -
Siddhesh Kadam TyBsc Advance Java
preferred sizes.
void setLocation(Point)
Set the position of the internal frame. (Inherited from
void setLocation(int,
Component).
int)
void
setBounds(Rectangle) Explicitly set the size and location of the internal frame.
void setBounds(int, int, (Inherited from Component).
int, int)
void
Explicitly set the size of the internal frame. (Inherited from
setSize(Dimension)
Component).
void setSize(int, int)
Set or get whether the internal frame is currently closed. The
void
argument to setClosed must be true. When reopening a closed
setClosed(boolean)
internal frame, you make it visible and add it to a container
boolean isClosed()
(usually the desktop pane you originally added it to).
Example 5:
//First internal Frame
import javax.swing.*;
import java.awt.Dimension;
public class CitiesPanel extends JInternalFrame {
public CitiesPanel() {
super("Select Cities :");
JPanel jp=new JPanel();
jp.add(new JButton("Mumbai"));
jp.add(new JButton("Delhi"));
jp.add(new JButton("Kolkatta"));
jp.add(new JButton("Chennai"));
getContentPane().add(jp);
setPreferredSize(new Dimension(300,300));
}
public void makeVisible(boolean val) {
setVisible(val);
}
}
//second internal frame
import javax.swing.*;
import java.awt.Dimension;
public class ColorPanel extends JInternalFrame {
public ColorPanel() {
super("Select color :");
JPanel jp=new JPanel();
jp.add(new JCheckBox("Red"));
jp.add(new JCheckBox("Green"));
jp.add(new JCheckBox("Blue"));
- 25 -
Siddhesh Kadam TyBsc Advance Java
jp.add(new JCheckBox("Yellow"));
getContentPane().add(jp);
setPreferredSize(new Dimension(300,300));
}
public void makeVisible(boolean val) {
setVisible(val);
}
}
//Third internal frame
import javax.swing.*;
import java.awt.Dimension;
public class FlavourPanel extends JInternalFrame {
public FlavourPanel() {
super("Select Flavour :");
JPanel jp=new JPanel();
JComboBox jcb=new JComboBox();
jcb.addItem("Vannila");
jcb.addItem("Strawbery");
jcb.addItem("Chocolate");
jp.add(jcb);
getContentPane().add(jp);
setPreferredSize(new Dimension(300,300));
}
public void makeVisible(boolean val) {
setVisible(val);
}
}
//Main Frame Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class IFrameDemo extends JFrame implements ActionListener
{
CitiesPanel c1=new CitiesPanel();
ColorPanel co1=new ColorPanel();
FlavourPanel f1=new FlavourPanel();
public IFrameDemo ()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
- 26 -
Siddhesh Kadam TyBsc Advance Java
- 27 -
Siddhesh Kadam TyBsc Advance Java
The JComponent class extends the Container class, which itself extends Component. The
Component class includes everything from providing layout hints to supporting painting
and events. The Container class has support for adding components to the container and
laying them out.
JComponent Features
The JComponent class provides the following functionality to its descendants:
• Tool tips - By specifying a string with the setToolTipText method, you can
provide help to users of a component. When the cursor pauses over the
component, the specified string is displayed in a small window that appears near
the component.
• Borders - The setBorder method allows you to specify the border that a
component displays around its edges.
• Keyboard-generated actions - Using the registerKeyboardAction method, you can
enable the user to use the keyboard, instead of the mouse, to operate the GUI. The
combination of character and modifier keys that the user must press to start an
action is represented by a KeyStroke object. The resulting action event must be
handled by an action listener. Each keyboard action works under exactly one of
three conditions: only when the actual component has the focus, only when the
component or one of its containers has the focus, or any time that anything in the
component's window has the focus.
• Application-wide pluggable look and feel - Behind the scenes, each JComponent
object has a corresponding ComponentUI object that performs all the drawing,
event handling, size determination, and so on for that JComponent. Exactly which
ComponentUI object is used depends on the current look and feel, which you can
set using the UIManager.setLookAndFeel method.
• Support for layout - To give you a way to set layout hints, the JComponent class
adds setter methods -- setPreferredSize, setMinimumSize, setMaximumSize,
setAlignmentX, and setAlignmentY.
• Double buffering - Double buffering smooths on-screen painting.
• Methods to increase efficiency - JComponent has a few methods that provide
more efficient ways to get information than the JDK 1.1 API allowed. The
methods include getX and getY, which you can use instead of getLocation; and
getWidth and getHeight, which you can use instead of getSize. It also adds one-
argument forms of getBounds, getLocation, and getSize for which you specify the
object to be modified and returned, letting you avoid unnecessary object creation.
These methods have been added to Component for Java 2 (JDK 1.2).
- 28 -
Siddhesh Kadam TyBsc Advance Java
A label object is a single line of read only text. A common use of JLabel objects is to
position descriptive text above or besides other components. JLabel extends the
JComponent class. It can display text and/or icon.
- 29 -
Siddhesh Kadam TyBsc Advance Java
JButton
A JButton class provides the functionality of a push button. JButton allows an icon, a
string or both to be associated with the push button. JButton is a subclass of
AbstractButton which extends JComponent.
Example 6:
import javax.swing.*;
- 30 -
Siddhesh Kadam TyBsc Advance Java
JCheckBox
A JCheckBox class provides the functionality of a Check box. Its immediate super class
is JToggleButton which provides support for 2 state buttons.
Constructor Purpose
JCheckBox(String) Create a JCheckBox instance. The string argument
JCheckBox(String, boolean) specifies the text, if any, that the check box should
JCheckBox(Icon) display. Similarly, the Icon argument specifies the
JCheckBox(Icon, boolean) image that should be used instead of the look and
JCheckBox(String, Icon) feel's default check box image. Specifying the boolean
JCheckBox(String, Icon, boolean) argument as true initializes the check box to be
JCheckBox() selected. If the boolean argument is absent or false,
then the check box is initially unselected.
String getActionCommand()
Returns the action command for this button.
String getText()
Returns the button's text.
boolean isSelected()
Returns the state of the button.
void setEnabled(boolean b)
Enables (or disables) the button.
void setSelected(boolean b)
Sets the state of the button.
void setText(String text)
Sets the button's text.
JRadioButton
A JRadioButton class provides the functionality of a radio button. Its immediate super
class is JToggleButton which provides support for 2 state buttons.
Constructor Purpose
JRadioButton(String) Create a JRadioButton instance. The string argument
JRadioButton(String, boolean) specifies the text, if any, that the radio button should
JRadioButton(Icon) display. Similarly, the Icon argument specifies the
JRadioButton(Icon, boolean) image that should be used instead of the look and
JRadioButton(String, Icon) feel's default radio button image. Specifying the
JRadioButton(String, Icon, boolean argument as true initializes the radio button to
boolean) be selected, subject to the approval of the
JRadioButton() ButtonGroup object. If the boolean argument is absent
or false, then the radio button is initially unselected.
Methods same as JCheckBox
- 31 -
Siddhesh Kadam TyBsc Advance Java
JComboBox
A component that combines a button or editable field and a drop-down list. The user can
select a value from the drop-down list, which appears at the user's request. If you make
the combo box editable, then the combo box includes an editable field into which the user
can type a value.
JList
A component that allows the user to select one or more objects from a list. A separate
model, ListModel, represents the contents of the list. It's easy to display an array or
vector of objects, using a JList constructor that builds a ListModel instance for you.
- 32 -
Siddhesh Kadam TyBsc Advance Java
Menus
JMenuBar
An implementation of a menu bar. You add JMenu objects to the menu bar to construct a
menu. When the user selects a JMenu object, its associated JPopupMenu is displayed,
allowing the user to select one of the JMenuItems on it.
JMenu
An implementation of a menu -- a popup window containing JMenuItems that is
displayed when the user selects an item on the JMenuBar. In addition to JMenuItems, a
JMenu can also contain JSeparators.
- 33 -
Siddhesh Kadam TyBsc Advance Java
JMenuItem
An implementation of an item in a menu. A menu item is essentially a button sitting in a
list. When the user selects the "button", the action associated with the menu item is
performed. A JMenuItem contained in a JPopupMenu performs exactly that function.
Example 7:
Create an animation with a single line, which changes its position in a clock-wise
direction. This line should produce an effect of a spinning line. In the same example
give option for clock-wise or anti-clock-wise spinning. Also provide options to start
and stop the animation. Demonstrate the animation on the screen.
- 34 -
Siddhesh Kadam TyBsc Advance Java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
LineAnimation()
{
super("Line Animation");
g=getGraphics();
mb=new MenuBar();
m1=new Menu("Motion");
m2=new Menu("Direction");
mi1=new MenuItem("Start");
mi2=new MenuItem("Stop");
mi3=new MenuItem("Clock-wise");
mi4=new MenuItem("Anti-Clock-wise");
t=new Timer(100,this);
mi1.addActionListener(this);
mi2.addActionListener(this);
mi3.addActionListener(this);
mi4.addActionListener(this);
m1.add(mi1); m1.add(mi2);
m2.add(mi3); m2.add(mi4);
mb.add(m1); mb.add(m2);
setMenuBar(mb);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
- 35 -
Siddhesh Kadam TyBsc Advance Java
if(ae.getSource()==mi1)
t.start();
if(ae.getSource()==mi2)
t.stop();
if(ae.getSource()==mi3)
incr=1;
if(ae.getSource()==mi4)
incr=-1;
}
- 36 -
Siddhesh Kadam TyBsc Advance Java
JTable
The JTable is used to display and edit regular two-dimensional tables of cells. The JTable
has many facilities that make it possible to customize its rendering and editing but
provides defaults for these features so that simple tables can be set up easily.
The JTable uses integers exclusively to refer to both the rows and the columns of the
model that it displays. The JTable simply takes a tabular range of cells and uses
getValueAt(int, int) to retrieve the values from the model during painting. By default,
columns may be rearranged in the JTable so that the view's columns appear in a different
order to the columns in the model. This does not affect the implementation of the model
at all: when the columns are reordered, the JTable maintains the new order of the
columns internally and converts its column indices before querying the model.
Constructors
JTable() Constructs a default JTable that is initialized with a
default data model, a default column model, and a
default selection model.
JTable(int numRows, Constructs a JTable with numRows and numColumns
int numColumns) of empty cells using DefaultTableModel.
JTable(Object[][] rowData, Constructs a JTable to display the values in the two
Object[] columnNames) dimensional array, rowData, with column names,
columnNames.
JTable(Vector rowData, Constructs a JTable to display the values in the Vector
Vector columnNames) of Vectors, rowData, with column names,
columnNames.
Methods
void clearSelection() Deselects all selected columns and rows.
int getColumnCount() Returns the number of columns in the column model.
String Returns the name of the column appearing in the view
getColumnName(int column) at column position column.
int getRowCount() Returns the number of rows in this table's model.
int getRowHeight() Returns the height of a table row, in pixels.
int getSelectedColumn() Returns the index of the first selected column, -1 if no
column is selected.
int getSelectedRow() Returns the index of the first selected row, -1 if no row
is selected.
Object getValueAt(int row, Returns the cell value at row and column.
int column)
void selectAll() Selects all rows, columns, and cells in the table.
- 37 -
Siddhesh Kadam TyBsc Advance Java
void setValueAt(Object aValue, Sets the value for the cell in the table model at row and
int row, int column) column.
JTextField
A text field is a basic text control that enables the user to type a small amount of text.
When the user indicates that text entry is complete (usually by pressing Enter), the text
field fires an action event. If you need to obtain more than one line of input from the user,
use a text area. The horizontal alignment of JTextField can be set to be left justified,
leading justified, centered, right justified or trailing justified. Right/trailing justification is
useful if the required size of the field text is smaller than the size allocated to it. This is
determined by the setHorizontalAlignment and getHorizontalAlignment methods. The
default is to be leading justified.
JTree
- 38 -
Siddhesh Kadam TyBsc Advance Java
Methods of MutuableTreeNode
void Adds child to the receiver at index.
insert(MutableTreeNode child,
int index)
void remove(int index) Removes the child at index from the receiver.
void Removes node from the receiver.
remove(MutableTreeNode node)
void Sets the parent of the receiver to newParent.
setParent(MutableTreeNode new
Parent)
Methods of DefaultMutableTreeNode
void Removes newChild from its parent and makes
add(MutableTreeNode newChild) it a child of this node by adding it to the end
of this node's child array.
int getChildCount() Returns the number of children of this node.
TreeNode[] getPath() Returns the path from the root, to get to this
node.
TreeNode getRoot() Returns the root of the tree that contains this
node.
boolean isRoot() Returns true if this node is the root of the tree.
• Create the object of the tree with the top most node as an argument.
• Use the add method to create the heirarchy.
• Create an object of JScrollpane and add the JTree to it. Add the scroll pane to the
content pane.
Event Handling
The JTree generates a TreeExpansionEvent which is in the package javax.swing.event.
the getPath() of this class returns a TreePath object that describes the path to the changed
node. The addTreeExpansionListener and removeTreeExpansionListener methods
- 39 -
Siddhesh Kadam TyBsc Advance Java
Example 8:
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
top.add(stream);
stream.add(arts); stream.add(comm); stream.add(science);
top.add(year);
year.add(fy); year.add(sy); year.add(ty);
tree=new JTree(top);
- 40 -
Siddhesh Kadam TyBsc Advance Java
tree.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
}// init()
- 41 -
Siddhesh Kadam TyBsc Advance Java
FlowLayout
The FlowLayout class puts components in a row, sized at their preferred size. If the
horizontal space in the container is too small to put all the components in one row, the
FlowLayout class uses multiple rows. If the container is wider than necessary for a row of
components, the row is, by default, centered horizontally within the container. To specify
that the row is to aligned either to the left or right, use a FlowLayout constructor that
takes an alignment argument. Another constructor of the FlowLayout class specifies how
much vertical or horizontal padding is put around the components.
Constructor Purpose
Constructs a new FlowLayout object with a centered alignment
FlowLayout()
and horizontal and vertical gaps with the default size of 5 pixels.
Creates a new flow layout manager with the indicated alignment
and horizontal and vertical gaps with the default size of 5 pixels.
The alignment argument can be FlowLayout.LEADING,
FlowLayout.CENTER, or FlowLayout.TRAILING. When the
FlowLayout(int align)
FlowLayout object controls a container with a left-to right
component orientation (the default), the LEADING value
specifies the components to be left-aligned and the TRAILING
value specifies the components to be right-aligned.
Creates a new flow layout manager with the indicated alignment
FlowLayout (int align, and the indicated horizontal and vertical gaps. The hgap and vgap
int hgap, int vgap) arguments specify the number of pixels to put between
components.
- 42 -
Siddhesh Kadam TyBsc Advance Java
Example 9:
import java.awt.*;
import javax.swing.*;
//<applet code="FlowDemo" height=320 width=140></applet>
public class FlowDemo extends JApplet
{
JLabel l1,l2;
JTextField name;
JTextArea add;
JButton ok,cancel;
name=new JTextField(10);
add=new JTextArea(10,8);
ok=new JButton("Ok");
cancel=new JButton("Cancel");
con.add(l1); con.add(name);
con.add(l2); con.add(add);
con.add(ok); con.add(cancel);
}//init
}//class
BorderLayout
A border layout lays out a container, arranging and resizing its components to fit in five
regions: north, south, east, west, and center. Each region may contain no more than one
component, and is identified by a corresponding constant: NORTH, SOUTH, EAST,
WEST, and CENTER. When adding a component to a container with a border layout, use
one of these five constants, for example:
- 43 -
Siddhesh Kadam TyBsc Advance Java
The components are laid out according to their preferred sizes and the constraints of the
container's size. The NORTH and SOUTH components may be stretched horizontally;
the EAST and WEST components may be stretched vertically; the CENTER component
may stretch both horizontally and vertically to fill any space left over.
Example 10:
import java.awt.*;
import javax.swing.*;
GridLayout
The GridLayout class is a layout manager that lays out a container's components in a
rectangular grid. The container is divided into equal-sized rectangles, and one component
is placed in each rectangle. When both the number of rows and the number of columns
have been set to non-zero values, either by a constructor or by the setRows and
setColumns methods, the number of columns specified is ignored. Instead, the number of
columns is determined from the specified number or rows and the total number of
components in the layout. So, for example, if three rows and two columns have been
specified and nine components are added to the layout, they will be displayed as three
- 44 -
Siddhesh Kadam TyBsc Advance Java
rows of three columns. Specifying the number of columns affects the layout only when
the number of rows is set to zero.
Constructor Purpose
Creates a grid layout with the specified number of rows
and columns. All components in the layout are given
GridLayout(int rows, int cols) equal size. One, but not both, of rows and cols can be
zero, which means that any number of objects can be
placed in a row or in a column.
Creates a grid layout with the specified number of rows
and columns. In addition, the horizontal and vertical
GridLayout(int rows, int cols,
gaps are set to the specified values. Horizontal gaps are
int hgap, int vgap)
places between each of columns. Vertical gaps are
placed between each of the rows.
Example 11:
import java.awt.*;
import javax.swing.*;
//<applet code="GridDemo" height=500 width=500></applet>
public class GridDemo extends JApplet
{
public void init()
{
Container con=getContentPane();
con.setLayout(new GridLayout(10,10));
con.setFont(new Font("sanserif",Font.BOLD,24));
for(int i=1;i<=10;i++)
{
for(int j=1;j<=10;j++)
{
con.add(new JButton(" "+i*j));
}//for2
}//for1
}//init
}//class
GridBagLayout
The GridBagLayout class is a flexible layout manager that aligns components vertically
and horizontally, without requiring that the components be of the same size. Each
GridBagLayout object maintains a dynamic rectangular grid of cells, with each
component occupying one or more cells, called its display area. Each component
managed by a grid bag layout is associated with an instance of GridBagConstraints that
specifies how the component is laid out within its display area.
- 45 -
Siddhesh Kadam TyBsc Advance Java
To use a grid bag layout effectively, you must customize one or more of the
GridBagConstraints objects that are associated with its components. You customize a
GridBagConstraints object by setting one or more of its instance variables:
• GridBagConstraints.gridx, GridBagConstraints.gridy
Specifies the cell at the upper left of the component's display area, where the
upper-left-most cell has address gridx = 0, gridy = 0.
• GridBagConstraints.gridwidth, GridBagConstraints.gridheight
Specifies the number of cells in a row (for gridwidth) or column (for gridheight)
in the component's display area.
• GridBagConstraints.fill
Used when the component's display area is larger than the component's requested
size to determine whether (and how) to resize the component.
• GridBagConstraints.ipadx, GridBagConstraints.ipady
Specifies the component's internal padding within the layout, how much to add to
the minimum size of the component.
• GridBagConstraints.insets
Specifies the component's external padding, the minimum amount of space
between the component and the edges of its display area.
• GridBagConstraints.anchor
Used when the component is smaller than its display area to determine where
(within the display area) to place the component.
• GridBagConstraints.weightx, GridBagConstraints.weighty
Used to determine how to distribute space, which is important for specifying
resizing behavior.
Example 12:
- 46 -
Siddhesh Kadam TyBsc Advance Java
import javax.swing.*;
import java.awt.*;
//<applet code = "GridBagDemo.class" height = 150 width = 200></applet>
public class GridBagDemo extends JApplet
{
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
Container con=getContentPane();
gbc.gridx=0;gbc.gridy=0;
con.add(new JButton("1"),gbc);
gbc.gridx=1;gbc.gridy=0;
con.add(new JButton("2"),gbc);
gbc.gridx=2;gbc.gridy=0;gbc.gridwidth = gbc.REMAINDER;
con.add(new JButton("3"),gbc);
gbc.gridx=0;gbc.gridy=1;
con.add(new JButton("4"),gbc);
gbc.gridx=0;gbc.gridy=2;gbc.gridheight = 2; gbc.gridwidth = 1;
con.add(new JButton("5"),gbc);
gbc.gridx=1;gbc.gridy=2;gbc.gridheight = 1; gbc.gridwidth = 2;
con.add(new JButton("6"),gbc);
gbc.gridx=1;gbc.gridy=3;gbc.gridwidth = 1;
con.add(new JButton("7"),gbc);
gbc.gridx=2;gbc.gridy=3;
con.add(new JButton("8"),gbc);
gbc.gridx=0;gbc.gridy=4;gbc.gridwidth = 2;
con.add(new JButton("9"),gbc);
gbc.gridx=2;gbc.gridy=4;gbc.gridwidth = 1;
con.add(new JButton("10"),gbc);
}
}
- 47 -
Siddhesh Kadam TyBsc Advance Java
CardLayout
A CardLayout object is a layout manager for a container. It treats each component in the
container as a card. Only one card is visible at a time, and the container acts as a stack of
cards. The first component added to a CardLayout object is the visible component when
the container is first displayed. The ordering of cards is determined by the container's
own internal ordering of its component objects. CardLayout defines a set of methods that
allow an application to flip through these cards sequentially, or to show a specified card.
The addLayoutComponent(java.awt.Component, java.lang.Object) method can be used to
associate a string identifier with a given card for fast random access.
Method Purpose
first (Container parent) Flips to the first card of the container.
Flips to the next card of the container. If the
next (Container parent) currently visible card is the last one, this method
flips to the first card in the layout.
Flips to the previous card of the container. If the
previous (Container parent) currently visible card is the first one, this method
flips to the last card in the layout.
last (Container parent) Flips to the last card of the container.
Flips to the component that was added to this
show (Container parent, String name) layout with the specified name, using the
addLayoutComponent method.
Example 13:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
- 48 -
Siddhesh Kadam TyBsc Advance Java
public CardLayoutDemo()
{
super("CardLayoutDemo");
Container con=getContentPane();
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
con.add(comboBoxPane, BorderLayout.NORTH);
con.add(cards, BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}//const
- 49 -
Siddhesh Kadam TyBsc Advance Java
BoxLayout
A layout manager that allows multiple components to be laid out either vertically or
horizontally. The components will not wrap so, for example, a vertical arrangement of
components will stay vertically arranged when the frame is resized.
Nesting multiple panels with different combinations of horizontal and vertical gives an
effect similar to GridBagLayout, without the complexity. The BoxLayout manager is
constructed with an axis parameter that specifies the type of layout that will be done.
There are two choices:
• X_AXIS - Components are laid out horizontally from left to right.
• Y_AXIS - Components are laid out vertically from top to bottom.
Example 14:
X_AXIS Y_AXIS
import java.awt.Container;
import javax.swing.*;
public class BoxLayoutDemo extends JFrame
{
public BoxLayoutDemo()
{
Container con=getContentPane();
con.setLayout(new BoxLayout(con,BoxLayout.Y_AXIS));
- 50 -
Siddhesh Kadam TyBsc Advance Java
Events :
An event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a GUI. E.g pressing a button
(ActionEvent), clicking a mouse (MouseEvent), entering a character (KeyEvent) etc.
Event Source :
A source is an object that generates an event. This occurs when the internal state of that
object changes. Source may generate more than one type of event. A source must register
in order for the listeners to recieve notifications about a specific type of event. The
general form is
public void addTypeListener(TypeListener tl)
Here type is the name of the event and tl is reference to the event listener. A source must
also provide a method that allows a listener to unregister in a specific type of event. the
general form is
public void removeTypeListener(TypeListener tl).
Event Listeners :
A listener is an object that is notified when an event occurs. It has two major
requirement:
• It must have been registered with one or more sources t recieve notification.
• It must implement methods to recieve and process these notifications.
An action event occurs, whenever an action is performed by the user. Examples: When
the user clicks a button, chooses a menu item, presses Enter in a text field. The result is
- 51 -
Siddhesh Kadam TyBsc Advance Java
that an actionPerformed message is sent to all action listeners that are registered on the
relevant component.
Example 15:
Write a program with three buttons on click of which a message should be displayed.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ActionDemo extends JFrame implements ActionListener
{
String msg="";
GridBagConstraints g1 = new GridBagConstraints();
public ActionDemo()
{
JButton b1=new JButton("Yes");
JButton b2=new JButton("No");
JButton b3=new JButton("Undecided");
Container con = getContentPane();
con.setLayout(new GridBagLayout());
g1.fill = GridBagConstraints.REMAINDER;
g1.gridx = 0; g1.gridy = 1;
con.add(b1,g1);
g1.gridx = 0; g1.gridy = 2;
- 52 -
Siddhesh Kadam TyBsc Advance Java
con.add(b2,g1);
g1.gridx = 0; g1.gridy = 3;
con.add(b3,g1);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
if(str.equals("Yes"))
msg = "You have clicked Yes";
else if(str.equals("No"))
msg = "You have clicked No";
else
msg = "You have clicked Undecided";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,100);
}
}
Example 16:
Write a program with three scroll bars on change of value the background color should
change.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Scroll()
{
super("Color Panel");
panel = (JPanel)getContentPane();
- 53 -
Siddhesh Kadam TyBsc Advance Java
panel.setLayout(new BorderLayout());
redscrollbar.addAdjustmentListener(this);
greenscrollbar.addAdjustmentListener(this);
bluescrollbar.addAdjustmentListener(this);
panel.add(redscrollbar, BorderLayout.EAST);
panel.add(greenscrollbar, BorderLayout.SOUTH);
panel.add(bluescrollbar, BorderLayout.WEST);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
Color c = new Color(
redscrollbar.getValue(),
greenscrollbar.getValue(),
bluescrollbar.getValue());
panel.setBackground(c);
}
public static void main(String args[])
{
Scroll obj = new Scroll();
obj.setVisible(true);
obj.setSize(800, 600);
}
}
The class that is interested in processing a component event either implements this
interface and all the methods it contains, or extends the abstract ComponentAdapter class
overriding only the methods of interest. The listener object created from that class is then
registered with a component using the component's addComponentListener method.
When the component's size, location, or visibility changes, the relevant method in the
listener object is invoked, and the ComponentEvent is passed to it.
- 54 -
Siddhesh Kadam TyBsc Advance Java
- 55 -
Siddhesh Kadam TyBsc Advance Java
- 56 -
Siddhesh Kadam TyBsc Advance Java
Example 17:
Write an application for Pizza Order. Fields : Crust, Toppings, Eat In or Take Away.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PizzaOrder extends JFrame implements ActionListener,ItemListener
{
JButton ok;
JRadioButton c1,c2;
JCheckBox ch1,ch2,ch3,ch4,ch5;
JLabel l1,l2;
JTextField t1;
JComboBox cob1;
String cstr = "";
Container con = getContentPane();
GridBagConstraints g1 = new GridBagConstraints();
public PizzaOrder()
{
con.setLayout(new GridBagLayout());
g1.fill = GridBagConstraints.BOTH;
ok = new JButton("OK");
c1 = new JRadioButton("Thick Crust");
c2 = new JRadioButton("Thin Crust");
l1 = new JLabel("Name");
t1 = new JTextField(20);
cob1 = new JComboBox();
g1.gridx = 0; g1.gridy = 0;
con.add(l1,g1);
g1.gridx = 1; g1.gridy = 0;
g1.gridwidth = 3;
con.add(t1,g1);
cob1.addItem("Take Away");
cob1.addItem("Eat");
g1.gridx = 1; g1.gridy = 4;
con.add(cob1,g1);
- 57 -
Siddhesh Kadam TyBsc Advance Java
g1.gridx = 1; g1.gridy = 6;
con.add(p1,g1);
g1.gridx = 1; g1.gridy = 9;
con.add(ch1,g1);
g1.gridx = 1; g1.gridy = 10;
con.add(ch2,g1);
g1.gridx = 1; g1.gridy = 11;
con.add(ch3,g1);
g1.gridx = 1; g1.gridy = 12;
con.add(ch4,g1);
g1.gridx = 1; g1.gridy = 13;
con.add(ch5,g1);
ch1.addItemListener(this);
ch2.addItemListener(this);
ch3.addItemListener(this);
ch4.addItemListener(this);
ch5.addItemListener(this);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
- 58 -
Siddhesh Kadam TyBsc Advance Java
if (source == ch1)
cstr = cstr + "\n"+ ch1.getLabel();
if (source == ch2)
cstr = cstr +"\n"+ ch2.getLabel();
if (source == ch3)
cstr = cstr +"\n"+ ch3.getLabel();
if (source == ch4)
cstr = cstr +"\n"+ ch4.getLabel();
if (source == ch5)
cstr = cstr +"\n"+ ch5.getLabel();
}//itemchanged
public void actionPerformed(ActionEvent ae)
{
String s1 = "Name = " +t1.getText();
s1 = s1 + "\nDelivery = "+ cob1.getSelectedItem();
if(c1.isSelected())
s1 = s1 + "\n Crust = " + c1.getLabel();
else
s1 = s1 + "\n Crust = " + c2.getLabel();
- 59 -
Siddhesh Kadam TyBsc Advance Java
The first kind of event is called a key-typed event. The second kind is either a key-
pressed or key-released event. In general, you react to only key-typed events unless you
need to know when the user presses keys that do not correspond to characters. For
example, to know when the user types a Unicode character — whether by pressing one
key such as 'a' or by pressing several keys in sequence — you handle key-typed events.
On the other hand, to know when the user presses the F1 key, or whether the user pressed
the '3' key on the number pad, you handle key-pressed events.
- 60 -
Siddhesh Kadam TyBsc Advance Java
- 61 -
Siddhesh Kadam TyBsc Advance Java
- 62 -
Siddhesh Kadam TyBsc Advance Java
Each internal frame event method has a single parameter: an InternalFrameEvent object.
The InternalFrameEvent class defines no generally useful methods. To get the internal
frame that fired the event, use the getSource method, which InternalFrameEvent inherits
from java.util.EventObject.
- 63 -
Siddhesh Kadam TyBsc Advance Java
Client/Server:
A server is a system that has some resource that can be shared. There are compute
servers, which provide computing power, print servers which manage a collection of
printers and webservers which stores web pages. A client is simply any other system that
wants to gain access in a particular server.
Reserved Sockets:
TCP/IP reserves the lower 1024 codes for specific protocols. Port number 21 is used for
FTP (File Transfer Protocol), 23 is used for Telnet, 25 is used for E-mail, 80 is used for
HTTP etc.
Proxy Servers:
A proxy server speaks the client side of a protocol to another server. This is often
required when clients have contained restrictions on which servers they can connect to.
Thus a client would connect to a proxyserver and the proxyserver would in turn
communicate with the client.
Internet Addressing:
An internet address is a number that uniquely identifies each computer on the net. Every
computer on the internet has an address. There are 32-bits in an IP address and we often
refer to them as a sequence of 4 numbers between 0 and 255 separated by dots.
The class URL represents a Uniform Resource Locator, a pointer to a resource on the
World Wide Web. A resource can be something as simple as a file or a directory, or it can
be a reference to a more complicated object such as a query to a database or to a search
engine. URL’s begin with a protocol specification such as HTTP of FTP, followed be
“://” and the host name along with optional file and port no. Java’s URL class is used to
create a URL object, which has several constructors and each throws a
MalformedURLException.
- 64 -
Siddhesh Kadam TyBsc Advance Java
Constructor Summary
URL(String spec)
Creates a URL object from the String representation.
URL(String protocol, String host, int port, String file)
Creates a URL object from the specified protocol, host, port number, and file.
URL(String protocol, String host, String file)
Creates a URL from the specified protocol name, host name, and file name.
Method Summary
String getAuthority()
Gets the authority part of this URL.
Object getContent()
Gets the contents of this URL.
String getFile()
Gets the file name of this URL.
String getHost()
Gets the host name of this URL, if applicable.
String getPath()
Gets the path part of this URL.
int getPort()
Gets the port number of this URL.
String getProtocol()
Gets the protocol name of this URL.
String getQuery()
Gets the query part of this URL.
String getRef()
Gets the anchor (also known as the "reference") of this URL.
String getUserInfo()
Gets the userInfo part of this URL.
URLConnection openConnection()
Returns a URLConnection object that represents a connection
to the remote object referred to by the URL.
InputStream openStream()
Opens a connection to this URL and returns an InputStream for
reading from that connection.
- 65 -
Siddhesh Kadam TyBsc Advance Java
URLConnection:
URL connection is a general purpose class for accessing the attributes of a remote
resource. Once a connection is established with the remote server, we can inspect the
properties of the remote object before actually transporting it locally. We can obtain an
object of URL connection with the help of openConnection() of the URL class.
Constructor Summary
URLConnection(URL url)
Constructs a URL connection to the specified URL.
Method Summary
abstract void connect()
Opens a communications link to the resource referenced by
this URL, if such a connection has not already been established.
String getContentEncoding()
Returns the value of the content-encoding header field.
int getContentLength()
Returns the value of the content-length header field.
String getContentType()
Returns the value of the content-type header field.
long getDate()
Returns the value of the date header field.
long getExpiration()
Returns the value of the expires header field.
String getHeaderField(int n)
Returns the value for the nth header field.
String getHeaderField(String name)
Returns the value of the named header field.
InputStream getInputStream()
Returns an input stream that reads from this open connection.
long getLastModified()
Returns the value of the last-modified header field.
OutputStream getOutputStream()
Returns an output stream that writes to this connection.
URL getURL()
Returns the value of this URLConnection's URL field.
- 66 -
Siddhesh Kadam TyBsc Advance Java
Example:
1) Define a class that displays information about a file URL like its type, encoding,
length, dates of creation, last modification and expiry. Additionally the class should
display the request method, response message and the response code for a Web
URL.
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.util.Date;
class URLDemo
{
long d;
public static void main(String args[])throws Exception
{
URL u=new URL("http://localhost:8080/index.html");
URLConnection uc=u.openConnection();
HttpURLConnection huc=(HttpURLConnection)uc;
- 67 -
Siddhesh Kadam TyBsc Advance Java
2) Define a class to download a file from the Internet and either copy it as a file on
the local machine, or output it to the screen.
import java.net.URL;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
class Download
{
public static void main(String args[])throws Exception
{
int b;
char c;
if(args.length==0)
throw new Exception("Invalid Number of argument");
- 68 -
Siddhesh Kadam TyBsc Advance Java
TCP/IP Sockets:
These are used to implement reliable, persistent, point to point, stream based connections
between hosts on the internet. The program at the 2 ends of the socket can write to and
read from the sockets.
Advantages:
• Easy to use.
• Used for 2 way communication.
• No parts of the transmission are lost.
Disadvantages:
• It requires setup time and shutdown time.
• Delivery is slower than datagram sockets.
There are two types of TCP/IP sockets. One is used for Servers and other is used for
clients.
Socket Class:
The socket class is designed to connect to a server socket. The creation of to a socket
object implicitly establishes a connection between client and server.
Constructor Summary
Socket(InetAddress address, int port)
Creates a stream socket and connects it to the specified port number at the specified IP
address.
Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
Creates a socket and connects it to the specified remote address on the specified remote
port.
Socket(String host, int port)
Creates a stream socket and connects it to the specified port number on the named host.
Socket(String host, int port, InetAddress localAddr, int localPort)
Creates a socket and connects it to the specified remote host on the specified remote port.
- 69 -
Siddhesh Kadam TyBsc Advance Java
Method Summary
void close()
Closes this socket.
void connect(SocketAddress endpoint)
Connects this socket to the server.
void connect(SocketAddress endpoint, int timeout)
Connects this socket to the server with a specified timeout value.
InetAddress getInetAddress()
Returns the address to which the socket is connected.
InputStream getInputStream()
Returns an input stream for this socket.
InetAddress getLocalAddress()
Gets the local address to which the socket is bound.
int getLocalPort()
Returns the local port to which this socket is bound.
OutputStream getOutputStream()
Returns an output stream for this socket.
int getPort()
Returns the remote port to which this socket is connected.
int getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this Socket, that is
the buffer size used by the platform for input on this Socket.
boolean isClosed()
Returns the closed state of the socket.
boolean isConnected()
Returns the connection state of the socket.
- 70 -
Siddhesh Kadam TyBsc Advance Java
ServerSocket Class:
The ServerSocket class is designed to be a listener which waits for the clients to connect.
When you create a ServerSocket it will register itself with the system as having as
interest in client connection.
Constructor Summary
ServerSocket(int port)
Creates a server socket, bound to the specified port.
ServerSocket(int port, int backlog)
Creates a server socket and binds it to the specified local port number, with the
specified backlog.
Method Summary
Socket accept()
Listens for a connection to be made to this socket and accepts it.
void close()
Closes this socket.
InetAddress getInetAddress()
Returns the local address of this server socket.
int getLocalPort()
Returns the port on which this socket is listening.
int getReceiveBufferSize()
Gets the value of the SO_RCVBUF option for this ServerSocket,
that is the proposed buffer size that will be used for Sockets accepted
from this ServerSocket.
boolean isClosed()
Returns the closed state of the ServerSocket.
- 71 -
Siddhesh Kadam TyBsc Advance Java
Example: Write a simple server that reports the current time (in textual form) to
any client that connects. This server should simply output the current time and close
the connection, without reading anything from the client. You need to choose a port
number that your service listens on.
import java.net.*;
import java.io.*;
import java.util.*;
class TimeServer
{
public static void main(String args[])throws Exception
{
ServerSocket s=new ServerSocket(1234);
Socket c=s.accept();
Calendar calendar = new GregorianCalendar();
PrintWriter out=new PrintWriter(c.getOutputStream());
out.println(new Date());
out.println("Time :");
out.print(
calendar.get(Calendar.HOUR)+"HRS."
+ calendar.get(Calendar.MINUTE)+"MIN."
+ calendar.get(Calendar.SECOND)+"SEC");
out.flush();
s.close();
c.close();
}
}
import java.net.*;
import java.io.*;
class TimeClient
{
public static void main(String args[])throws Exception
{
Socket c=new Socket(InetAddress.getLocalHost(),1234);
BufferedReader br=new BufferedReader(new
InputStreamReader(c.getInputStream()));
String userInput;
while((userInput=br.readLine())!=null)
{
System.out.println(userInput);
}
c.close();
}
}
- 72 -
Siddhesh Kadam TyBsc Advance Java
UDP Sockets:
Datagram sockets are not connection oriented. Here we send self contained packets of
data. Each packet contains information that identifies in addition to the content of the
message.
Advantages:
• Does not require setup time and shutdown time.
• Delivery is faster than TCP/IP sockets.
Disadvantages:
• Datagram sockets cannot be used for two way communication.
• Parts of the transmission are lost.
A datagram socket is the sending or receiving point for a packet delivery service. Each
packet send or receive on a datagramsocket is individually addressed or routed. Multiple
packets send from 1 machine may be routed differently and may arrive in any order.
Constructor Summary
DatagramSocket()
Constructs a datagram socket and binds it to any available port on the local host machine.
DatagramSocket(int port)
Constructs a datagram socket and binds it to the specified port on the local host machine.
DatagramSocket(int port, InetAddress laddr)
Creates a datagram socket, bound to the specified local address.
Method Summary
void close()
Closes this datagram socket.
void connect(InetAddress address, int port)
Connects the socket to a remote address for this socket.
InetAddress getInetAddress()
Returns the address to which this socket is connected.
InetAddress getLocalAddress()
Gets the local address to which the socket is bound.
int getLocalPort()
Returns the port number on the local host to which this socket is
bound.
int getPort()
- 73 -
Siddhesh Kadam TyBsc Advance Java
DatagramPacket:
DatagramPackets are use to implement a connection less packet delivery service.
Each message is routed from one machine to another based on the information contained
within that packet.
Constructor Summary
DatagramPacket(byte[] buf, int length)
Constructs a DatagramPacket for receiving packets of length length.
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
Constructs a datagram packet for sending packets of length length to the specified
port number on the specified host.
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
Constructs a datagram packet for sending packets of length length with offset set
to the specified port number on the specified host.
Method Summary
InetAddress getAddress()
Returns the IP address of the machine to which this datagram is
being sent or from which the datagram was received.
byte[] getData()
Returns the data buffer.
int getLength()
Returns the length of the data to be sent or the length of the data
received.
int getOffset()
Returns the offset of the data to be sent or the offset of the data
received.
int getPort()
Returns the port number on the remote host to which this datagram
- 74 -
Siddhesh Kadam TyBsc Advance Java
- 75 -
Siddhesh Kadam TyBsc Advance Java
Example: Write a Java program for datagram communication between two client
machines using Unreliable Datagram Protocol.
import java.net.*;
import java.io.*;
class DataGramServer{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int cp=1510,sp=1511;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(sp);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
InetAddress ia=InetAddress.getByName(args[0]);
while(true){
String str=br.readLine();
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,cp));
if(str.length()==0){
ds.close();
break;
}
}
}//main
}//class
import java.net.*;
import java.io.*;
class DataGramClient{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int cp=1510,sp=1511;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(cp);
System.out.print("Client is waiting for server to send data....");
while(true){
DatagramPacket dp=new DatagramPacket(buffer,buffer.length);
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength());
if(dp.getLength()==0)
break;
System.out.println(str);
}
}//main
}//class
- 76 -
Siddhesh Kadam TyBsc Advance Java
The Beans Development Kit (BDK) is a pure Java application whose only dependency is
the Java Development Kit (JDK) 1.1. The BDK provides support for the JavaBeans APIs,
a test container (the “BeanBox” to test Bean behavior), sample Beans complete with their
source code, the JavaBeans Specification.
The BeanBox
The BeanBox is a sample container for testing Beans. The BeanBox handles visible
Beans, those Beans that have a visual element, and invisible Beans, those Beans that are
purely computational objects. When you start the BeanBox, a ToolBox of sample Beans
is displayed.
- 77 -
Siddhesh Kadam TyBsc Advance Java
Properties
A property is a single public attribute. Properties can be read/write, read-only or write-
only. There are several types of properties: simple, indexed, bound, and constrained.
Simple Properties
A simple property represents a single value and can be defined with a pair of get/set
methods. A property’s name is derived from the method names. For example the method
names setX and getX indicate a property named “X”. A method name is X by convention
indicates that “X” is a boolean property.
Indexed Properties
An indexed property represents an array of values. Property element get/set methods take
an integer index parameter. The property may also support getting and setting the entire
array at once.
The BDK 1.0 BeanBox does not support indexed properties.
- 78 -
Siddhesh Kadam TyBsc Advance Java
Bound Properties
A bound property notifies other objects when its value changes. Each time its value is
changed, the property fires a PropertyChange event which contains the property name,
old, and new values. Notification granularity is per bean, not per property. dataSet is an
indexed property set entire array set one element of array get entire array get one element
of array
- 79 -
Siddhesh Kadam TyBsc Advance Java
Constrained Properties
An object with constrained properties allows other objects to veto a constrained property
value change. Constrained property listeners can veto a change by throwing a
PropertyVetoException.
A Bean property is constrained when any change to that property can be vetoed. Usually
an outside object exercises the right to veto, but the Bean itself can also veto a property
change. The JavaBeans API provides an event mechanism, very similar to the bound
property mechanism that allows objects to veto a Bean's property changes.
- 80 -
Siddhesh Kadam TyBsc Advance Java
• Fire property change events at those interested listeners when a property change is
proposed. The event should be fired before the actual property change takes place.
This gives each listener a chance to veto the proposed change. The
PropertyChangeEvent is fired by a call to each listeners vetoableChange method.
• If a listener vetoes, then make sure that any other listeners can revert to the old
value. This means reissuing the vetoableChange call to all the listeners, with a
PropertyChangeEvent containing the old value.
Note that, in general, constrained properties should also be bound properties. When a
constrained property change does occur, a PropertyChangeEvent can be sent via
PropertyChangeListener.propertyChange to signal all VetoableChangeListener Beans
that the change has taken effect. This lets all the vetoable change listeners know that the
change was not vetoed by any listener.
The JellyBean demo Bean has a constrained property. We will its code to illustrate the
steps in implementing constrained properties. Here are the steps to implement
constrained properties in your Beans:
1) Import the java.beans package. This gives you access to the
VetoableChangeSupport class.
2) Instantiate a VetoableChangeSupport object within your Bean:
private VetoableChangeSupport vetos = new VetoableChangeSupport(this);
VetoableChangeSupport manages a list of VetoableChangeListener objects, and
fires property change events at each object in the list when a change occurs to a
constrained property.
3) Implement methods to maintain the property change listener list. These merely
wrap calls to the VetoableChangeSupport object's methods:
public void addVetoableChangeListener(VetoableChangeListener l){
vetos.addVetoableChangeListener(l);
}
public void removeVetoableChangeListener(VetoableChangeListener l) {
vetos.removeVetoableChangeListener(l);
}
4) Write a property's setter method to fire a property change event when the property
is changed. This includes adding a throws clause to the setter method's signature.
JellyBean's setPriceInCents method looks like this:
public void setPriceInCents(int newPriceInCents) throws PropertyVetoException
{
int oldPriceInCents = ourPriceInCents;
- 81 -
Siddhesh Kadam TyBsc Advance Java
// First tell the vetoers about the change. If anyone objects, we don't catch the
//exception but just let if pass on to our caller.
vetos.fireVetoableChange("priceInCents",
new Integer(oldPriceInCents),
new Integer(newPriceInCents));
// No-one vetoed, so go ahead and make the change.
ourPriceInCents = newPriceInCents;
changes.firePropertyChange("priceInCents",
new Integer(oldPriceInCents),
new Integer(newPriceInCents));
}
Note that setPriceInCents stores the old price, because both the old and new prices must
be passed to fireVetoableChange. Also note that the primitive int prices are converted to
Integer objects.
public void fireVetoableChange(String propertyName,
Object oldValue,
Object newValue)
throws PropertyVetoException
These values are then bundled into a PropertyChangeEvent object sent to each listener.
The old and new values are treated as Object values, so if they are primitive types such as
int, you must use the object version such as java.lang.Integer.
Now you are ready to implement a Bean that listens for constrained property changes.
Note that the VetoableChangeListener object is often an adapter class. The adapter class
implements the VetoableChangeListener interface and the vetoableChange method. This
adapter is added to the constrained Bean's listener list, intercepts the vetoableChange call,
and calls the target Bean method that exercises veto power. You'll see an example of this
in the next section.
- 82 -
Siddhesh Kadam TyBsc Advance Java
Events
The BeanBox uses either design pattern introspection or a BeanInfo class to discover
what events a Bean can fire.
These methods let a source Bean know where to fire events. The source Bean then fires
events at those listener Beans using the methods for those particular interfaces. For
example, if a source Bean registers ActionListener objects, it will fire events at those
objects by calling the actionPerformed method on those listeners.
2) You can explicitly "publish" the events a Bean fires by using a class that implements
the BeanInfo interface.
The BeanBox generates an adapter class that interposes between the event source and
target. The adapter class implements the appropriate event listener interface (and so is the
actual listener), catches the event fired by the button, and then calls the selected target
Bean method.
Example:
//Creating an event class to store two numbers
import java.util.*;
public class NumEvent extends EventObject
{
public int num1,num2;
public NumEvent(Object o,int num1,int num2) {
super(o);
this.num1=num1;
this.num2=num2;
}
}
/* Creating the listener interface that has to be implemented by classes that might have to
perform some arithmetic operation with two numbers */
import java.util.*;
public interface NumEnteredListener extends EventListener
{
public void arithmeticPerformed(NumEvent ne);
}
- 83 -
Siddhesh Kadam TyBsc Advance Java
/* Code the bean that accepts two numbers. When the user enters the two numbers and
clicks the ‘ok’ button, all target applications that use this bean have to be notified */
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public NumberBean()
{
setLayout(new FlowLayout());
add(l1);add(t1);add(l2);add(t2);add(ok);
ok.addActionListener(this);
}
public void addNumListener(NumEnteredListener nel)
{
this.nel=nel;
}
public void fireNumEvent(NumEvent ne)
{
nel.arithmeticPerformed(ne);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==ok)
{
int f1=Integer.parseInt(t1.getText());
int f2=Integer.parseInt(t2.getText());
ne=new NumEvent(ok,f1,f2);
fireNumEvent(ne);
}
}
}
/* A sample target applications that listens to the number data entry event and display the
result of adding the two numbers */
import java.util.*;
- 84 -
Siddhesh Kadam TyBsc Advance Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public ArithmeticPerformer()
{
super("Calculations");
nb=new NumberBean();
getContentPane().add(nb);
nb.addNumListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
BeanInfo Interface
You can explicitly expose a Bean's features in a separate, associated class that
implements the BeanInfo interface. By associating a BeanInfo class with your Bean, you
can:
• Expose only those features you want to expose.
• Rely on BeanInfo to expose some Bean features while relying on low-level
reflection to expose others.
• Associate an icon with the target Bean.
• Specify a customizer class.
• Segregate features into normal and expert categories.
• Provide a more descriptive display name, or additional information about a Bean
feature.
• BeanInfo defines methods that return descriptors for each property, method, or
event that you want exposed. Here's the prototypes for these methods:
- 85 -
Siddhesh Kadam TyBsc Advance Java
PropertyDescriptor[] getPropertyDescriptors();
MethodDescriptor[] getMethodDescriptors();
EventSetDescriptor[] getEventSetDescriptors();
Each of these methods returns an array of descriptors for each feature.
Feature Descriptors
BeanInfo classes contain descriptors that precisely describe the target Bean's features.
The BDK implements the following descriptor classes:
• FeatureDescriptor is the base class for the other descriptor classes. It declares the
aspects common to all descriptor types.
• BeanDescriptor describes the target Bean's class type and name, and describes the
target Bean's customizer class if it exists.
• PropertyDescriptor describes the target Bean's properties.
• IndexedPropertyDescriptor is a subclass of PropertyDescriptor, and describes the
target Bean's indexed properties.
• EventSetDescriptor describes the events the target Bean fires.
• MethodDescriptor describes the target Bean's methods.
• ParameterDescriptor describes method parameters.
The BeanInfo interface declares methods that return arrays of the above descriptors. If
you leave a descriptor out, that property, event or method will not be exposed. In other
words, you can selectively expose properties, events, or methods by leaving out those you
don't want exposed.
Example:
/* A simple text editor that creates a list of two values */
import java.beans.*;
import javax.swing.*;
import java.awt.*;
- 86 -
Siddhesh Kadam TyBsc Advance Java
/* The tFont property of the Test class is associated with the TextFontEditor classs */
import java.beans.*;
import javax.swing.*;
import java.awt.*;
- 87 -
Siddhesh Kadam TyBsc Advance Java
Customizers
When you use a Bean Customizer, you get complete control over how to configure or edit
a Bean. A Customizer is like an application that specifically targets a Bean's
customization. Sometimes properties are insufficient for representing a Bean's
configurable attributes. Customizers are used where sophisticated instructions would be
needed to change a Bean, and where property editors are too primitive to achieve Bean
customization.
If a Bean that has an associated Customizer is dropped into the BeanBox, you will notice
a "Customize..." item on the Edit menu.
Persistence
To make fields in a Bean class persistent, simply define the class as implementing
java.io.Serializable.
The fields in any instance of a Bean which implements Serializable will automatically be
saved. You need do nothing else. You can prevent selected fields from being saved by
marking them transient or static; transient and static variables are not saved.
What to Save
Generally, a Bean should store the state of any exposed properties. Selected internal state
variables may also be saved. Beans should not, however, store pointers to external Beans.
If you need to make changes to a class, which alter its persistence, you might define a
version id field which can be checked at runtime. For example, static final long
SerialVersionUID 348749695999L;
- 88 -
Siddhesh Kadam TyBsc Advance Java
Example 1: Create a Java bean that accepts numeric data as text validates it as a
number and then makes the numeric value available for further processing.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.beans.*;
}
public void actionPerformed(ActionEvent e)
{
try
{
setValue(Double.parseDouble(getText()));
}
catch(NumberFormatException ex)
{
select(0,getText().length());
}//catch
}
public double getValue()
{
return value;
}
public void setValue(double newValue)
{
double oldValue=value;
value=newValue;
setText(""+newValue);
firePropertyChange("value",oldValue,newValue);
}
}
- 89 -
Siddhesh Kadam TyBsc Advance Java
Example 2: Create a Java bean that displays multiple lines of text with margins and
alignment.
import java.awt.*;
import java.lang.*;
import java.util.StringTokenizer;
g.setColor(Color.blue);
g.drawLine(LeftMargin,0,LeftMargin,1000);
g.drawLine(0,TopMargin,1000,TopMargin);
g.setColor(Color.black);
StringTokenizer st=new StringTokenizer(str,"|");
String sPrint;
FontMetrics fm=g.getFontMetrics();
int nextLY;
nextLY=fm.getAscent();
- 90 -
Siddhesh Kadam TyBsc Advance Java
//if(st.hasMoreTokens()==true)
while(st.hasMoreTokens()==true)
{
sPrint=st.nextToken();
alignStr(fm,sPrint,g,nextLY);
nextLY +=fm.getHeight();
}
else
g.drawString(str,LeftMargin,(nextLY + TopMargin));
}//paint
int iWidth=fm.stringWidth(s);
if(cl=="L")
{
g.drawString(s,LeftMargin, nextLY + TopMargin);
}
if(cl=="R")
{
g.drawString(s, (getWidth()-2 - iWidth), nextLY + TopMargin);
}
if(cl=="C")
{
g.drawString(s,(getWidth()-2-LeftMargin-iWidth)/2,nextLY+TopMargin);
}
}//align
}//class
- 91 -
Siddhesh Kadam TyBsc Advance Java
Example 3: Develop a Java bean that is a 2D shape filled with color, which could
take on different shapes. The color changes randomly each time the mouse is clicked
on the bean. Also provide a BeanInfo class, which will help in introspection and to
load a custom property editor for the shape property.
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
- 92 -
Siddhesh Kadam TyBsc Advance Java
- 93 -
Siddhesh Kadam TyBsc Advance Java
import java.util.*;
import java.beans.*;
import java.beans.*;
public class ShapeEditor extends PropertyEditorSupport
{
private String[] options={"Circle","Square","Rectangle"};
- 94 -
Siddhesh Kadam TyBsc Advance Java
Example 4: Create an invisible Java bean that multiplies the values of two of its
properties and places the product in a third as a read only property.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.beans.*;
import java.io.*;
public class MulFunction implements Serializable
{
public double a,b,c;
public PropertyChangeSupport p=new PropertyChangeSupport(this);
public double getA() {
return a;
}
public void setA(double newA) {
double oldA=a;
a=newA;
p.firePropertyChange("a",new Double(oldA),new Double(newA));
multiply();
}
public double getB() {
return b;
}
public void setB(double newB) {
double oldB=b;
b=newB;
p.firePropertyChange("b",new Double(oldB),new Double(newB));
multiply();
}
public double getC() {
return c;
}
public void multiply() {
double oldC=c;
c=a*b;
p.firePropertyChange("c",new Double(oldC),new Double(c));
}
public void addPropertyChangeListener(PropertyChangeListener l) {
p.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
p.removePropertyChangeListener(l);
}
}
- 95 -
Siddhesh Kadam TyBsc Advance Java
- 96 -
Siddhesh Kadam TyBsc Advance Java
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.sybase.jdbc.SybDriver");
}
catch(ClassNotFoundException cnfe)
{
System.err.println("Error loading driver: " + cnfe);
}
One of the beauties of the JDBC approach is that the database server requires no changes
whatsoever. Instead, the JDBC driver (which is on the client) translates calls written in
the Java programming language into the native format required by the server. This
approach means that you have to obtain a JDBC driver specific to the database you are
using and that you will need to check the vendor’s documentation for the fully qualified
class name to use. In principle, you can use Class.forName for any class in your
CLASSPATH. In practice, however, most JDBC driver vendors distribute their drivers
inside JAR files. So, during development be sure to include the path to the driver JAR file
in your CLASSPATH setting. For deployment on a Web server, put the JAR file in the
WEB-INF/lib directory of your Web application. Check with your Web server
administrator, though. Often, if multiple Web applications are using the same database
drivers, the administrator will place the JAR file in a common directory used by the
server. For example, in Apache Tomcat, JAR files common to multiple applications can
be placed in install_dir/common/lib.
Figure 1 illustrates two common JDBC driver implementations. The first approach is a
JDBC-ODBC bridge, and the second approach is a pure Java implementation. A driver
that uses the JDBC-ODBC bridge approach is known as a Type I driver. Since many
databases support Open DataBase Connectivity (ODBC) access, the JDK includes a
JDBC-ODBC bridge to connect to databases. However, you should use the vendor’s pure
Java driver, if available, because the JDBC-ODBC driver implementation is slower than a
pure Java implementation. Pure Java drivers are known as Type IV. The JDBC
specification defines two other driver types, Type II and Type III; however, they are less
common. Type 2 - drivers 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. Type 3
- drivers 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.
- 97 -
Siddhesh Kadam TyBsc Advance Java
- 98 -
Siddhesh Kadam TyBsc Advance Java
The Connection class includes other useful methods, which we briefly describe below.
• prepareStatement - Creates precompiled queries for submission to the database.
• prepareCall - Accesses stored procedures in the database.
• rollback/commit - Controls transaction management.
• close - Terminates the open connection.
• isClosed - Determines whether the connection timed out or was explicitly closed.
Most, but not all, database drivers permit multiple concurrent Statement objects to be
open on the same connection.
The following list summarizes commonly used methods in the Statement class.
• executeQuery - Executes an SQL query and returns the data in a ResultSet. The
ResultSet may be empty, but never null.
• executeUpdate - Used for UPDATE, INSERT, or DELETE commands. Returns
the number of rows affected, which could be zero. Also provides support for Data
Definition Language (DDL) commands, for example, CREATE TABLE, DROP
TABLE, and ALTER TABLE.
• executeBatch - Executes a group of commands as a unit, returning an array with
the update counts for each command. Use addBatch to add a command to the
batch group. Note that vendors are not required to implement this method in their
driver to be JDBC compliant.
- 99 -
Siddhesh Kadam TyBsc Advance Java
• setQueryTimeout - Specifies the amount of time a driver waits for the result
before throwing an SQLException.
• getMaxRows/setMaxRows - Determines the number of rows a ResultSet may
contain. Excess rows are silently dropped. The default is zero for no limit.
In addition to using the methods described here to send arbitrary commands, you can use
a Statement object to create parameterized queries by which values are supplied to a
precompiled fixed-format query using Prepared Statements.
Here is an example that prints the values of the first two columns and the first name and
last name, for all rows of a ResultSet.
while(resultSet.next())
{
System.out.println( resultSet.getString(1) + " " +
resultSet.getString(2) + " " +
resultSet.getString("firstname") + " "
resultSet.getString("lastname") );
}
We suggest that when you access the columns of a ResultSet, you use the column name
instead of the column index. That way, if the column structure of the table changes, the
code interacting with the ResultSet will be less likely to fail. In JDBC 1.0, you can only
move forward in the ResultSet; however, in JDBC 2.0, you can move forward (next) and
backward (previous) in the ResultSet as well as move to a particular row (relative,
absolute).
- 100 -
Siddhesh Kadam TyBsc Advance Java
• getXxx - Returns the value from the column specified by the column name or
column index as an Xxx Java type (see java.sql.Types). Can return 0 or null if the
value is an SQL NULL.
• wasNull - Checks whether the last getXxx read was an SQL NULL. This check is
important if the column type is a primitive (int, float, etc.) and the value in the
database is 0. A zero value would be indistinguishable from a database value of
NULL, which is also returned as a 0. If the column type is an object (String, Date,
etc.), you can simply compare the return value to null.
• findColumn - Returns the index in the ResultSet corresponding to the specified
column name.
• getRow - Returns the current row number, with the first row starting at 1 (JDBC
2.0).
• getMetaData - Returns a ResultSetMetaData object describing the ResultSet.
ResultSetMetaData gives the number of columns and the column names.
The getMetaData method is particularly useful. Given only a ResultSet, you have to
know the name, number, and type of the columns to be able to process the table properly.
For most fixed-format queries, this is a reasonable expectation. For ad hoc queries,
however, it is useful to be able to dynamically discover high-level information about the
result. That is the role of the ResultSetMetaData class: it lets you determine the number,
names, and types of the columns in the ResultSet.
ResultSetMetaData does not include information about the number of rows; however, if
your driver complies with JDBC 2.0, you can call last on the ResultSet to move the
cursor to the last row and then call getRow to retrieve the current row number. In JDBC
1.0, the only way to determine the number of rows is to repeatedly call next on the
ResultSet until it returns false.
- 101 -
Siddhesh Kadam TyBsc Advance Java
Example 1 – Write a JDBC program to create a table and insert records into it.
import java.sql.*;
Statement st = con.createStatement();
st.executeUpdate(str);
System.out.println("Table Created");
System.out.println("Values Inserted");
}
catch(Exception e){System.out.println("Error"+e.getMessage());}
}
}
- 102 -
Siddhesh Kadam TyBsc Advance Java
Example 2 – Write a JDBC program to fetch values and display them on screen.
import java.sql.*;
Connection con =
DriverManager.getConnection("jdbc:odbc:First");
Statement st = con.createStatement();
while(sel.next())
{
String name = sel.getString(1)
;
String pass = sel.getString(2);
System.out.println(name+" "+pass);
}
}
catch(Exception e)
{
System.out.println("Errooorrrr"+e.getMessage());
}
}
}
- 103 -
Siddhesh Kadam TyBsc Advance Java
Example 3 - Write a JDBC program to get the columns names and row data from a
table.
import java.sql.*;
class FetchData
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:sidd");
System.out.println("Connecting to database....");
Statement st=con.createStatement();
ResultSet rs=
st.executeQuery("select * from dept order by deptno asc");
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Displaying Values....");
for(int i=1;i<=rsmd.getColumnCount();i++)
System.out.print(rsmd.getColumnName(i)+"\t");
System.out.println("\n");
con.commit();
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
st.close();
}
catch(Exception a){System.out.println("ERROR"+a.getMessage());}
}
}
- 104 -
Siddhesh Kadam TyBsc Advance Java
Example 4 - Write a java code to accept the query from user at command line
argument. Then process this query and using ResultSet and ResultSetMetaData
class. Display the result on the screen with proper title of the fields and the fields
separator should be ‘|’ (pipe) symbol.
import java.sql.*;
import java.io.*;
class CLAQuery
{
public static void main(String args[])throws SQLException
{
Connection con;
int i;
String str;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:sidd");
Statement st=con.createStatement();
BufferedReader br=new BufferedReader((
new InputStreamReader(System.in)));
System.out.println("Enter The Query");
str=br.readLine();
ResultSet rs=st.executeQuery(str);
ResultSetMetaData md=rs.getMetaData();
int num=md.getColumnCount();
System.out.print("\n");
for(i=1;i<=num;i++)
System.out.print(md.getColumnName(i)+"\t\t");
System.out.println("");
while(rs.next())
{
for(i=1;i<=num;i++)
System.out.print(rs.getString(i)+"\t\t");
System.out.print("\n");
}
}
catch(Exception e)
{
System.out.println("Error1:"+e.getMessage());
}
}
}
- 105 -
Siddhesh Kadam TyBsc Advance Java
Example 5 - Create a JFrame, which will add data of Friends (Name, DOB, Address
and Tel. No.) to the database and on click of Show All button displays the records
that are there in the database.
import javax.swing.*;
import java.awt.*;
import java.sql.*;
import java.lang.*;
class FriendDatabase extends JFrame implements ActionListener
{
JLabel lblDob,lblName,lblDetails,lblPhno,lblHead;
JTextField txtName,txtDob,txtPhno;
JTextArea txtDetails;
JButton cmdAdd,cmdShowAll,cmdExit;
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc=new GridBagConstraints();
Container con=getContentPane();
public FriendDatabase()
{
lblHead=new JLabel("Information");
lblName=new JLabel("Friend Name");
lblDob=new JLabel("DOB");
lblDetails=new JLabel("Address");
lblPhno=new JLabel("Phno");
txtName=new JTextField("");
txtDob=new JTextField("");
txtDetails=new JTextArea(2,2);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(txtDetails,v,h);
txtPhno=new JTextField("");
cmdAdd=new JButton("Add");
cmdAdd.addActionListener(this);
cmdShowAll=new JButton("Show All");
cmdShowAll.addActionListener(this);
cmdExit=new JButton("Exit");
cmdExit.addActionListener(this);
con.setLayout(new GridBagLayout());
gbc.fill=GridBagConstraints.BOTH;
gbc.weightx=1.0;
gbc.insets=new Insets(20,20,20,20);
- 106 -
Siddhesh Kadam TyBsc Advance Java
gbc.gridx=1;gbc.gridy=0;
con.add(lblHead,gbc);
gbc.gridx=0;gbc.gridy=1;
con.add(lblName,gbc);
gbc.gridx=1;gbc.gridy=1;
con.add(txtName,gbc);
gbc.gridx=0;gbc.gridy=2;
con.add(lblDob,gbc);
gbc.gridx=1;gbc.gridy=2;
con.add(txtDob,gbc);
gbc.gridx=0;gbc.gridy=3;
con.add(lblDetails,gbc);
gbc.gridx=1;gbc.gridy=3;
con.add(jsp,gbc);
gbc.gridx=0;gbc.gridy=4;
con.add(lblPhno,gbc);
gbc.gridx=1;gbc.gridy=4;
con.add(txtPhno,gbc);
gbc.fill=GridBagConstraints.NONE;
gbc.gridx=0;gbc.gridy=5;
con.add(cmdAdd,gbc);
gbc.gridx=1;gbc.gridy=5;
con.add(cmdShowAll,gbc);
gbc.gridx=2;gbc.gridy=5;
con.add(cmdExit,gbc);
}
public void actionPerformed(ActionEvent ae)
{
Object obj=ae.getSource();
if(obj==cmdAdd)
{ Connection con;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:sidd");
- 107 -
Siddhesh Kadam TyBsc Advance Java
txtName.setText("");
txtDob.setText("");
txtDetails.setText("");
txtPhno.setText("");
ps.close();
con.close();
}
catch(Exception e)
{
System.out.println("Error:"+e.getMessage());
}
}
if(obj==cmdExit)
{
System.exit(0);
}
if(obj==cmdShowAll)
{
ShowAll as=new ShowAll(this,true);
}
}
- 108 -
Siddhesh Kadam TyBsc Advance Java
super(f,m);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:sidd");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from FriendDatabase");
i=0;
while(rs.next())
{
for(j=0;j<=3;j++)
{
Object obj=rs.getObject(j+1);
rows[i][j]=obj.toString();
System.out.print(""+obj.toString()+"\t");
}
i++;
}
t=new JTable(rows,cols);
int v1=ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h1=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
p=new JScrollPane(t,v1,h1);
Container con1=getContentPane();
con1.add(p,BorderLayout.CENTER);
setSize(300,300);
setVisible(true);
}
catch(Exception e)
{
System.out.println("Error2:"+e.getMessage());
}
}
}
- 109 -
Siddhesh Kadam TyBsc Advance Java
• Read the explicit data sent by the client - The end user normally enters the data in
an HTML form on a Web page. However, the data could also come from an
applet or a custom HTTP client program.
• Read the implicit HTTP request data sent by the browser - Figure 1 shows a
single arrow going from the client to the Web server (the layer where servlets and
JSP execute), but there are really two varieties of data: the explicit data that the
end user enters in a form and the behind-the-scenes HTTP information. Both
varieties are critical. The HTTP information includes cookies, information about
media types and compression schemes the browser understands, and so forth.
• Generate the results - This process may require talking to a database, executing an
RMI or EJB call, invoking a Web service, or computing the response directly.
Your real data may be in a relational database. Fine. But your database probably
doesn’t speak HTTP or return results in HTML, so the Web browser can’t talk
directly to the database. Even if it could, for security reasons, you probably would
not want it to. The same argument applies to most other applications. You need
the Web middle layer to extract the incoming data from the HTTP stream, talk to
the application, and embed the results inside a document.
• Send the explicit data (i.e., the document) to the client - This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images),
or even a compressed format like gzip that is layered on top of some other
underlying format. But, HTML is by far the most common format, so an
important servlet/JSP task is to wrap the results inside of HTML.
• Send the implicit HTTP response data - Figure 1 shows a single arrow going from
the Web middle layer (the servlet or JSP page) to the client. But, there are really
two varieties of data sent: the document itself and the behind-the-scenes HTTP
information. Again, both varieties are critical to effective development. Sending
HTTP response data involves telling the browser or other client what type of
document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.
- 110 -
Siddhesh Kadam TyBsc Advance Java
There are a number of reasons why Web pages need to be built on-the-fly:
• The Web page is based on data sent by the client - For instance, the results page
from search engines and order confirmation pages at online stores are specific to
particular user requests. You don’t know what to display until you read the data
that the user submits. Just remember that the user submits two kinds of data:
explicit (i.e., HTML form data) and implicit (i.e., HTTP request headers). Either
kind of input can be used to build the output page. In particular, it is quite
common to build a user-specific page based on a cookie value.
• The Web page is derived from data that changes frequently - If the page changes
for every request, then you certainly need to build the response at request time. If
it changes only periodically, however, you could do it two ways: you could
periodically build a new Web page on the server (independently of client
requests), or you could wait and only build the page when the user requests it. The
right approach depends on the situation, but sometimes it is more convenient to do
the latter: wait for the user request. For example, a weather report or news
headlines site might build the pages dynamically, perhaps returning a previously
built page if that page is still up to date.
• The Web page uses information from corporate databases or other server-side
sources - If the information is in a database, you need server-side processing even
if the client is using dynamic Web content such as an applet. Imagine using an
applet by itself for a search engine site: “Downloading 50 terabyte applet, please
wait!” Obviously, that is silly; you need to talk to the database. Going from the
client to the Web tier to the database (a three-tier approach) instead of from an
applet directly to a database (a two-tier approach) provides increased flexibility
and security with little or no performance penalty. After all, the database call is
usually the rate-limiting step, so going through the Web server does not slow
things down. In fact, a three-tier approach is often faster because the middle tier
can perform caching and connection pooling.
Efficient
With traditional CGI, a new process is started for each HTTP request. If the CGI program
itself is relatively short, the overhead of starting the process can dominate the execution
time. With servlets, the Java virtual machine stays running and handles each request with
a lightweight Java thread, not a heavyweight operating system process. Similarly, in
traditional CGI, if there are N requests to the same CGI program, the code for the CGI
program is loaded into memory N times. With servlets, however, there would be N
threads, but only a single copy of the servlet class would be loaded. This approach
reduces server memory requirements and saves time by instantiating fewer objects.
Finally, when a CGI program finishes handling a request, the program terminates. This
approach makes it difficult to cache computations, keep database connections open, and
- 111 -
Siddhesh Kadam TyBsc Advance Java
perform other optimizations that rely on persistent data. Servlets, however, remain in
memory even after they complete a response, so it is straightforward to store arbitrarily
complex data between client requests.
Convenient
Servlets have an extensive infrastructure for automatically parsing and decoding HTML
form data, reading and setting HTTP headers, handling cookies, tracking sessions, and
many other such high-level utilities. In CGI, you have to do much of this yourself.
Besides, if you already know the Java programming language, why learn Perl too?
You’re already convinced that Java technology makes for more reliable and reusable
code than does Visual Basic, VBScript, or C++. Why go back to those languages for
server-side programming?
Powerful
Servlets support several capabilities that are difficult or impossible to accomplish with
regular CGI. Servlets can talk directly to the Web server, whereas regular CGI programs
cannot, at least not without using a server-specific API. Communicating with the Web
server makes it easier to translate relative URLs into concrete path names, for instance.
Multiple servlets can also share data, making it easy to implement database connection
pooling and similar resource-sharing optimizations. Servlets can also maintain
information from request to request, simplifying techniques like session tracking and
caching of previous computations.
Portable
Servlets are written in the Java programming language and follow a standard API.
Servlets are supported directly or by a plugin on virtually every major Web server.
Consequently, servlets written for, say, Macromedia JRun can run virtually unchanged on
Apache Tomcat, Microsoft Internet Information Server (with a separate plugin), IBM
WebSphere, iPlanet Enterprise Server, Oracle9i AS, or StarNine WebStar. They are part
of the Java 2 Platform, Enterprise Edition (J2EE), so industry support for servlets is
becoming even more pervasive.
Inexpensive
A number of free or very inexpensive Web servers are good for development use or
deployment of low- or medium-volume Web sites. Thus, with servlets and JSP you can
start with a free or inexpensive server and migrate to more expensive servers with high-
performance capabilities or advanced administration utilities only after your project
meets initial success. This is in contrast to many of the other CGI alternatives, which
require a significant initial investment for the purchase of a proprietary package. Price
and portability are somewhat connected.
- 112 -
Siddhesh Kadam TyBsc Advance Java
Secure
One of the main sources of vulnerabilities in traditional CGI stems from the fact that the
programs are often executed by general-purpose operating system shells. So, the CGI
programmer must be careful to filter out characters such as backquotes and semicolons
that are treated specially by the shell. Implementing this precaution is harder than one
might think, and weaknesses stemming from this problem are constantly being uncovered
in widely used CGI libraries. A second source of problems is the fact that some CGI
programs are processed by languages that do not automatically check array or string
bounds. For example, in C and C++ it is perfectly legal to allocate a 100-element array
and then write into the 999th “element,” which is really some random part of program
memory. So, programmers who forget to perform this check open up their system to
deliberate or accidental buffer overflow attacks. Servlets suffer from neither of these
problems. Even if a servlet executes a system call (e.g., with Runtime.exec or JNI) to
invoke a program on the local operating system, it does not use a shell to do so. And, of
course, array bounds checking and other memory protection features are a central part of
the Java programming language.
- 113 -
Siddhesh Kadam TyBsc Advance Java
should return the normal HTTP headers, but no associated document). You don’t
normally need to implement doHead because the system automatically calls doGet and
uses the resultant status line and header settings to answer HEAD requests. However, it is
occasionally useful to implement doHead so that you can generate responses to HEAD
requests (i.e., requests from custom clients that want just the HTTP headers, not the
actual document) more quickly—without building the actual document output.
- 114 -
Siddhesh Kadam TyBsc Advance Java
- 115 -
Siddhesh Kadam TyBsc Advance Java
Example 3: Write a Servlet that accepts name and age of student sent from an
HTML document and displays them on screen.
//Student.html file
<html>
<head><title>Student Information</title>
</head>
<form name=frm method=get action=http:\\localhost:8080\Servlet\Student.class>
</form>
<body>
<table>
<tr><td>Student Name</td><td><input type=text name=txtName></td></tr>
<tr><td>Student Age</td><td><input type=text name=txtAge></td></tr>
</table>
<input type=submit name=submit>
</body>
</html>
//Student.java file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Student extends HttpServlet
{
public void doGet(HttpServletResponse res,HttpServletRequest req)
throws ServletException,IOException
{
res.setContentType("text/html");
String name=(String)req.getParameter("txtName");
String age=(String)req.getParameter("txtAge");
PrintWriter out=res.getWriter();
out.println(“Name = ”+name);
out.println(“Age= ”+age);
}
}//class
- 116 -
Siddhesh Kadam TyBsc Advance Java
- 117 -
Siddhesh Kadam TyBsc Advance Java
PrintWriter out=res.getWriter();
while(e.hasMoreElements())
{
String name=(String)e.nextElement();
out.println(name);
String[] value=req.getParameterValues(name);
for(int i=0;i<value.length;i++)
{
out.print(value[i]+"\t");
}
}
}//try
catch(Exception e)
{
System.out.println("ERROR "+e.getMessage());
}
}
}
Example 5: Write two servlets in which one servlet will display a form in which data
entry can be done for the field’s dept-no, dept-name and location. In the same form
place a button called as submit and on click of that button this record should be
posted to the table called as DEPT in the database. This inserting of record should
be done in another servlet. The second servlet should also display all the previous
record entered in the database.
//Part I
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DeptForm extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
try
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<Html><Head><Title>Department Info</Title></Head>");
out.println("<Form name=frm method="+"POST"+"
action=DeptEntry.class>");
out.println("DepartmentNo: <input type=text name=txtNo><br>");
out.println("DepartmentName: <input type=text name=txtName><br>");
out.println("Location: <input type=text name=txtLoc><br>");
out.println("<input type=submit name=Submit>");
- 118 -
Siddhesh Kadam TyBsc Advance Java
//Part II
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DeptEntry extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException
{
String a,b,c,d,e,f;
int i;
Connection con;
try
{
res.setContentType("text/html");
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:odbc:First”);
String Query="insert into dept Values(?,?,?)";
Statement st=con.createStatement();
PreparedStatement ps;
ps=con.prepareStatement(Query);
a=(String)req.getParameter("txtNo");
b=(String)req.getParameter("txtName");
c=(String)req.getParameter("txtLoc");
ps.setString(1,a);
ps.setString(2,b);
ps.setString(3,c);
ps.executeUpdate();
PrintWriter out=res.getWriter();
ResultSet rs=st.executeQuery("select * from dept");
ResultSetMetaData md=rs.getMetaData();
int num=md.getColumnCount();
out.println("<html><body><table border=1><tr>");
- 119 -
Siddhesh Kadam TyBsc Advance Java
for(i=1;i<=num;i++)
{
out.print("<th>"+md.getColumnName(i)+"</th>");
}
out.println("</tr>");
while(rs.next())
{ d=rs.getString(1);
e=rs.getString(2);
f=rs.getString(3);
out.println("<tr><td>"); out.println(d);
out.println("</td><td>"); out.println(e);
out.println("</td><td>"); out.println(f);
out.println("</td></tr>");
}
out.println("</table>");
con.commit();
out.println("<a href=DeptForm.class>BACK</a>");
out.println("</body></html>");
}
catch (Exception ae)
{
System.out.println(ae.getMessage());
}
}
}
Response Headers
Setting the HTTP response headers often goes hand in hand with setting the status codes
in the status line. For example, all the “document moved” status codes (300 through 307)
have an accompanying Location header, and a 401 (Unauthorized) code always includes
an accompanying WWW-Authenticate header. However, specifying headers can also
play a useful role even when no unusual status code is set. Response headers can be used
to specify cookies, to supply the page modification date (for client-side caching), to
instruct the browser to reload the page after a designated interval, to give the file size so
that persistent HTTP connections can be used, to designate the type of document being
generated, and to perform many other tasks.
- 120 -
Siddhesh Kadam TyBsc Advance Java
Cache-Control: This useful header tells the browser or other client the circumstances in
which the response document can safely be cached.
Connection: A value of close for this response header instructs the browser not to use
persistent HTTP connections.
Content-Disposition: The Content-Disposition header lets you request that the browser
ask the user to save the response to disk in a file of the given name.
Content-Encoding: This header indicates the way in which the page was encoded during
transmission.
- 121 -
Siddhesh Kadam TyBsc Advance Java
Content-Type: The Content-Type header gives the MIME (Multipurpose Internet Mail
Extension) type of the response document. Setting this header is so common that there is
a special method in HttpServletResponse for it: setContentType.
Expires: This header stipulates the time at which the content should be considered out-of-
date and thus no longer be cached. A servlet might use this header for a document that
changes relatively frequently, to prevent the browser from displaying a stale cached
value.
Last-Modified: This very useful header indicates when the document was last changed.
Location: This header, which should be included with all responses that have a status
code in the 300s, notifies the browser of the document address.
Pragma: Supplying this header with a value of no-cache instructs HTTP 1.0 clients not to
cache the document.
Refresh: This header indicates how soon (in seconds) the browser should ask for an
updated page. For example, to tell the browser to ask for a new copy in 30 seconds, you
would specify a value of 30 with response.setIntHeader("Refresh", 30);
Retry-After: This header can be used in conjunction with a 503 (Service Unavailable)
response to tell the client how soon it can repeat its request.
Set-Cookie: The Set-Cookie header specifies a cookie associated with the page. Each
cookie requires a separate Set-Cookie header. Servlets should not use
response.setHeader("Set-Cookie", ...) but instead should use the special-purpose
addCookie method of HttpServletResponse.
- 122 -
Siddhesh Kadam TyBsc Advance Java
Example 6: Write a servlet that creates Excel spreadsheet comparing apples and
oranges.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ApplesAndOranges extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("application/vnd.ms-excel");
PrintWriter out = response.getWriter();
out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");
out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");
out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
}
}
Request Headers
HTTP request headers are distinct from the form (query) data. Form data results directly
from user input and is sent as part of the URL for GET requests and on a separate line for
POST requests. Request headers, on the other hand, are indirectly set by the browser and
are sent immediately following the initial GET or POST request line. For instance, the
following example shows an HTTP request that might result from a user submitting a
book-search request to a servlet at http://www.somebookstore.com/servlet/Search. The
request includes the headers Accept, Accept-Encoding, Connection, Cookie, Host,
Referer, and User-Agent, all of which might be important to the operation of the servlet,
but none of which can be derived from the form data or deduced automatically: the
servlet needs to explicitly read the request headers to make use of this information.
- 123 -
Siddhesh Kadam TyBsc Advance Java
Following is a summary.
• getCookies - The getCookies method returns the contents of the Cookie header,
parsed and stored in an array of Cookie objects.
• getAuthType and getRemoteUser - The getAuthType and getRemoteUser
methods break the Authorization header into its component pieces.
• getContentLength - The getContentLength method returns the value of the
Content-Length header (as an int).
• getContentType - The getContentType method returns the value of the Content-
Type header (as a String).
• getDateHeader and getIntHeader - The getDateHeader and getIntHeader methods
read the specified headers and then convert them to Date and int values,
respectively.
• getHeaderNames - Rather than looking up one particular header, you can use the
getHeaderNames method to get an Enumeration of all header names received on
this particular request.
• getHeaders - In most cases, each header name appears only once in the request.
Occasionally, however, a header can appear multiple times, with each occurrence
listing a separate value. Accept-Language is one such example. You can use
getHeaders to obtain an Enumeration of the values of all occurrences of the
header.
Finally, in addition to looking up the request headers, you can get information on the
main request line itself (i.e., the first line in the example request just shown), also by
means of methods in HttpServletRequest. Here is a summary of the four main methods.
getMethod - The getMethod method returns the main request method (normally, GET or
POST, but methods like HEAD, PUT, and DELETE are possible).
getRequestURI - The getRequestURI method returns the part of the URL that comes after
the host and port but before the form data. For example, for a URL of
http://randomhost.com/servlet/search.BookSearch?subject=jsp, getRequestURI would
return "/servlet/search.BookSearch".
getQueryString - The getQueryString method returns the form data. For example, with
http://randomhost.com/servlet/search.BookSearch?subject=jsp, getQueryString would
return "subject=jsp".
getProtocol - The getProtocol method returns the third part of the request line, which is
generally HTTP/1.0 or HTTP/1.1. Servlets should usually check getProtocol before
specifying response headers (Chapter 7) that are specific to HTTP 1.1.
- 124 -
Siddhesh Kadam TyBsc Advance Java
Example 7: Write a program which shows all the request headers sent on the
current request
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
- 125 -
Siddhesh Kadam TyBsc Advance Java
Status Codes
The HTTP response status line consists of an HTTP version, a status code, and an
associated message. Since the message is directly associated with the status code and the
HTTP version is determined by the server, all a servlet needs to do is to set the status
code. A code of 200 is set automatically, so servlets don’t usually need to specify a status
code at all. When they do want to, they use response.setStatus, response.sendRedirect, or
response.sendError.
Setting a status code does not necessarily mean that you omit the document. For example,
although most servers automatically generate a small File Not Found message for 404
responses, a servlet might want to customize this response. Again, remember that if you
do send output, you have to call setStatus or sendError first.
- 126 -
Siddhesh Kadam TyBsc Advance Java
200–299: Values in the 200s signify that the request was successful.
300–399: Values in the 300s are used for files that have moved and usually include a
Location header indicating the new address.
Examples:
100 (Continue) - If the server receives an Expect request header with a value of 100-
continue, it means that the client is asking if it can send an attached document in a
follow-up request. In such a case, the server should either respond with status 100
(SC_CONTINUE) to tell the client to go ahead or use 417
(SC_EXPECTATION_FAILED) to tell the browser it won’t accept the document. This
status code is new in HTTP 1.1.
200 (OK) - A value of 200 (SC_OK) means that everything is fine; the document follows
for GET and POST requests. This status is the default for servlets; if you don’t use
setStatus, you’ll get 200.
202 (Accepted)
204 (No Content)
205 (Reset Content)
- 127 -
Siddhesh Kadam TyBsc Advance Java
400 (Bad Request) - A 400 (SC_BAD_REQUEST) status indicates bad syntax in the
client request.
401 (Unauthorized) - A value of 401 (SC_UNAUTHORIZED) signifies that the client
tried to access a password-protected page but that the request did not have proper
identifying information in the Authorization header. The response must include a WWW-
Authenticate header.
403 (Forbidden) - A status code of 403 (SC_FORBIDDEN) means that the server refuses
to supply the resource, regardless of authorization. This status is often the result of bad
file or directory permissions on the server.
404 (Not Found) - The infamous 404 (SC_NOT_FOUND) status tells the client that no
resource could be found at that address. This value is the standard “no such page”
response. It is such a common and useful response that there is a special method for it in
the HttpServletResponse class: sendError("message"). The advantage of sendError over
setStatus is that with sendError, the server automatically generates an error page showing
the error message. 404 errors need not merely say “Sorry, the page cannot be found.”
Instead, they can give information on why the page couldn’t be found or supply search
boxes or alternative places to look.
405 (Method Not Allowed)
415 (Unsupported Media Type)
417 (Expectation Failed)
Example 8: Write a Servlet that sends IE users to the Netscape home page and
Netscape (and all other) users to the Microsoft home page
import javax.servlet.*;
import javax.servlet.http.*;
public class WrongDestination extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String userAgent = request.getHeader("User-Agent");
if ((userAgent != null) &&(userAgent.indexOf("MSIE") != -1))
response.sendRedirect("http://home.netscape.com");
else
response.sendRedirect("http://www.microsoft.com");
}
}
- 128 -
Siddhesh Kadam TyBsc Advance Java
Cookies
Cookies are small bits of textual information that a Web server sends to a browser and
that the browser later returns unchanged when visiting the same Web site or domain. By
letting the server read information it sent the client previously, the site can provide
visitors with a number of conveniences such as presenting the site the way the visitor
previously customized it or letting identifiable visitors in without their having to reenter a
password.
Benefits of Cookies
There are four typical ways in which cookies can add value to your site. We summarize
these benefits below:
• Identifying a user during an e-commerce session - This type of short-term
tracking is so important that another API is layered on top of cookies for this
purpose.
• Remembering usernames and passwords - Cookies let a user log in to a site
automatically, providing a significant convenience for users of unshared
computers.
• Customizing sites - Sites can use cookies to remember user preferences.
• Focusing advertising - Cookies let the site remember which topics interest certain
users and show advertisements relevant to those interests.
• Setting the maximum age - If you want the browser to store the cookie on disk
instead of just keeping it in memory, you use setMaxAge to specify how long (in
seconds) the cookie should be valid.
• Placing the Cookie into the HTTP response headers - You use
response.addCookie to accomplish this. If you forget this step, no cookie is sent to
the browser!
To read the cookies that come back from the client, you should perform the following
two tasks, which are summarized below:
• Call request.getCookies. This yields an array of Cookie objects.
• Loop down the array, calling getName on each one until you find the cookie of
interest. You then typically call getValue and use the value in some application-
specific way.
- 129 -
Siddhesh Kadam TyBsc Advance Java
Example 9: Write a program which stores a Cookie and the read the cookie to
display the information.
//Part I
<html><body><center>
<form name=form1 method=get action=”AddCookieServlet”>
<B>Enter a Value</B>
<input type=text name=data>
<input type=submit>
</form></center></body></html>
- 130 -
Siddhesh Kadam TyBsc Advance Java
//Part II
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
String data = req.getParametar();
Cookie c = new Cookie("My Cookie",data);
res.addCookie(c);
res.setCountentType("text/html");
PrintWriter out = res.getWriter();
out.println("My Cookie has been set to");
out.println(data);
}
}
//Part III
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookie extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException
{
Cookie c[] = req.getCookie();
res.setContentType("text/html");
PrintWriter out = res.getWriter();
for(int i = 0; i < c.length; i++)
{
String name = c[i].getName();
String value = c[i].getValue();
out.println(name +"\t"+ value);
}
}
}
HttpSession
It provides a way to identify a user across more than one page request or visit to a Web
site. The servlet engine uses this interface to create a session between an HTTP client and
an HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user. A session usually corresponds to one user, who
may visit a site many times. The server can maintain a session either by using cookies or
by rewriting URLs.
- 131 -
Siddhesh Kadam TyBsc Advance Java
• Bind objects to sessions, allowing you to use an online shopping cart to hold data
that persists across multiple user connections
• Data that the application provides, accessed using this interface and stored using a
dictionary-like interface
An HTTP session represents the server's view of the session. The server considers a
session new under any of these conditions:
• The client does not yet know about the session
• The session has not yet begun
• The client chooses not to join the session, for example, if the server supports only
cookies and the client rejects the cookies the server sends
Method Summary
String getId()
Returns a string containing the unique identifier assigned to this session.
Object getValue(String name)
Returns the object bound with the specified name in this session or null
if no object of that name exists.
String[] getValueNames()
Returns an array containing the names of all the objects bound to this
session.
boolean isNew()
Returns true if the Web server has created a session but the client has
not yet joined.
void putValue(String name, Object value)
Binds an object to this session, using the name specified.
void removeValue(String name)
Removes the object bound with the specified name from this session.
- 132 -
Siddhesh Kadam TyBsc Advance Java
Example 10: Create a form, which accepts user information such as name and
background color. Session allows storing the client information about name and
background. If the user is new then display the page asking for name and
background else set the background and find number of visits to the page.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SessionServlet extends HttpServlet
{
public void service(HttpServletResponse res,HttpServletRequest req)
throws IOException,ServletException
{
try {
res.setContentType("Text/Html");
Integer hitCount;
PrintWriter out=res.getWriter();
HttpSession s=req.getSession(true);
if(s.isNew())
{
out.println("<Html>");
out.println("<Form method="+"GET"+" action
=http://localhost:8080/servlet/SessionServlet>");
out.println("<b>Please select bgcolor</b>");
out.println("<input type=radio name=optColor value=red>Red");
out.println("<input type=radio name=optColor value=green>Green");
out.println("<input type=radio name=optColor value=blue>Blue");
out.println("<input type=text name=txtName>");
out.println("<br><br>");
out.println("<input type=submit value=Submit>");
out.println("</form></Html>");
}//if
else
{
String name=(String)req.getParameter("txtName");
String color=(String)req.getParameter("optColor");
if(name!=null && color!=null)
{
out.println("Name: "+name);
hitCount=new Integer(1);
out.println("<a href=SessionServlet>SessionServlet");
s.putValue("txtName",name);
s.putValue("optColor",color);
s.putValue("Hit",hitCount);
}
- 133 -
Siddhesh Kadam TyBsc Advance Java
else
{
hitCount=(Integer)s.getValue("Hit");
hitCount=new Integer(hitCount.intValue()+1);
s.putValue("Hit",hitCount);
out.println("<Html><body text=cyan bgcolor="
+s.getValue("optColor")+">");
out.println("You Have Been Selected"
+s.getValue("optColor")+"Color");
out.println("<br><br>Your Name Is"
+s.getValue("txtName"));
out.println("<br><br>Number Of Visits==>"+hitCount);
out.println("<br><br>");
out.println("<a href=SessionServlet>SessionServlet</a>");
out.println("</body></html>");
}
}
}//try
catch(Exception e){}
}//service
}//class
- 134 -
Siddhesh Kadam TyBsc Advance Java
JSP Advantages
• Separation of static from dynamic content: With servlets, the logic for generation
of the dynamic content is an intrinsic part of the servlet itself, and is closely tied
to the static presentation templates responsible for the user interface. Thus, even
minor changes made to the UI typically result in the recompilation of the servlet.
This tight coupling of presentation and content results in brittle, inflexible
applications. However, with JSP, the logic to generate the dynamic content is kept
separate from the static presentation templates by encapsulating it within external
JavaBeans components. These are then created and used by the JSP page using
special tags and scriptlets. When a page designer makes any changes to the
presentation template, the JSP page is automatically recompiled and reloaded into
the web server by the JSP engine.
• Write Once Run Anywhere: JSP technology brings the "Write Once, Run
Anywhere" paradigm to interactive Web pages. JSP pages can be moved easily
across platforms, and across web servers, without any changes.
• Dynamic content can be served in a variety of formats: There is nothing that
mandates the static template data within a JSP page to be of a certain format.
Consequently, JSP can service a diverse clientele ranging from conventional
browsers using HTML/DHTML, to handheld wireless devices like mobile phones
and PDAs using WML, to other B2B applications using XML.
• Completely leverages the Servlet API: If you are a servlet developer, there is very
little that you have to "unlearn" to move over to JSP. In fact, servlet developers
are at a distinct advantage because JSP is nothing but a high-level abstraction of
servlets. You can do almost anything that can be done with servlets using JSP--
but more easily!
- 135 -
Siddhesh Kadam TyBsc Advance Java
Example 1: Write a JSP page to display the current date and time.
<Html>
<Head>
<Title>JSP Expressions</Title>
</Head>
<Body>
<H2>JSP Expressions</H2>
<ul>
<li>Current time: <%= new java.util.Date() %>
<li>Server: <%= application.getServerInfo() %>
<li>Session Id: <%= session.getId() %>
<li>The <code>test param</code> form parameter:
<%= request.getParameter("testParam")%>
</ul>
</Body>
</Html>
- 136 -
Siddhesh Kadam TyBsc Advance Java
JSP Architecture
The purpose of JSP is to provide a declarative, presentation-centric method of developing
servlets. As noted before, the JSP specification itself is defined as a standard extension on
top the Servlet API. Consequently, it should not be too surprisingly that under the covers,
servlets and JSP pages have a lot in common.
Typically, JSP pages are subject to a translation phase and a request processing phase.
The translation phase is carried out only once, unless the JSP page changes, in which case
it is repeated. Assuming there were no syntax errors within the page, the result is a JSP
page implementation class file that implements the Servlet interface, as shown below.
The translation phase is typically carried out by the JSP engine itself, when it receives an
incoming request for the JSP page for the first time. Many details of the translation phase,
like the location where the source and class files are stored are implementation
dependent.
The JSP page implementation class file extends HttpJspBase, which in turn implements
the Servlet interface. Observe how the service method of this class, _jspService(),
essentially inlines the contents of the JSP page. Although _jspService() cannot be
overridden, the developer can describe initialization and destroy events by providing
implementations for the jspInit() and jspDestroy() methods within their JSP pages.
Once this class file is loaded within the servlet container, the _jspService() method is
responsible for replying to a client's request. By default, the _jspService() method is
dispatched on a separate thread by the servlet container in processing concurrent client
requests, as shown below:
- 137 -
Siddhesh Kadam TyBsc Advance Java
In the Model 1 architecture, the incoming request from a web browser is sent directly to
the JSP page, which is responsible for processing it and replying back to the client. There
is still separation of presentation from content, because all data access is performed using
beans.
Although the Model 1 architecture is suitable for simple applications, it may not be
desirable for complex implementations. Indiscriminate usage of this architecture usually
leads to a significant amount of scriptlets or Java code embedded within the JSP page,
especially if there is a significant amount of request processing to be performed. While
this may not seem to be much of a problem for Java developers, it is certainly an issue if
- 138 -
Siddhesh Kadam TyBsc Advance Java
your JSP pages are created and maintained by designers--which is usually the norm on
large projects. Another downside of this architecture is that each of the JSP pages must be
individually responsible for managing application state and verifying authentication and
security.
The advantage of this architecture is that there is no processing logic within the
presentation component itself; it is simply responsible for retrieving any objects or beans
that may have been previously created by the controller, and extracting the dynamic
content within for insertion within its static templates. Consequently, this clean
separation of presentation from content leads to a clear delineation of the roles and
responsibilities of the developers and page designers on the programming team. Another
benefit of this approach is that the front components present a single point of entry into
the application, thus making the management of application state, security, and
presentation uniform and easier to maintain.
- 139 -
Siddhesh Kadam TyBsc Advance Java
Example 2: Write a JSP file, which displays the parameters passed to the file.
Register.jsp
<Html>
<Head>
<Title>Register</Title>
</Head>
<form method=get action="http://localhost:8080/StudentInfo.jsp">
<table border=1>
<tr><td>Name:</td><td> <input type=text name=txtName></td>
<tr><td>Age: </td><td><input type=text name=txtAge></td>
<tr><td>Tel Nos: </td><td><input type=text name=txtTelNo></td>
<tr><td><input type=submit></td><td> <input type=reset></td>
</table>
</form>
</html>
StudentInfo.jsp
<html>
<head>
<Title>Student Info</Title>
</Head>
<Body>
<table border=1>
<tr><td>Name</td><td> <%= request.getParameter("txtName") %></td></tr>
<tr><td>Age</td><td><%= request.getParameter("txtAge") %></td></tr>
<tr><td>Tel No</td><td><%= request.getParameter("txtTelNo") %></td></tr>
</table>
</body>
</html>
Example 3: Write a JSP page, which displays three text boxes for Department
Number, Department Name and Location. On click of the submit button call
another JSP page which will enter the values in the database with the help of
PreparedStatement class. Also use jspInit() and jspDestroy() to open and close the
connection. (Register.jsp).
DeptForm.jsp
<html>
<Head><title>Department Form</title>
</head>
<body>
<form method=GET action="http://localhost:8080/Register1.jsp">
<table>
<tr><td>DepartmentNo: </td><td> <input type=text name=txtNo></td></tr>
<tr><td>DepartmentName: </td><td><input type=text name=txtName></td></tr>
- 140 -
Siddhesh Kadam TyBsc Advance Java
Register1.jsp
<%@ page import="java.sql.*" %>
<%! String a,b,c,d,e,f,Query; %>
<%! Connection con;
Statement st;
PreparedStatement ps; %>
<%! int i,num; %>
<%!
public void jspInit()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:ty289");
st=con.createStatement();
Query="insert into Dept values(?,?,?)";
ps=con.prepareStatement(Query);
}
catch(Exception e){System.out.println("Error: "+e.getMessage());}
}
%>
<%
a=(String)request.getParameter("txtNo");
b=(String)request.getParameter("txtName");
c=(String)request.getParameter("txtLoc");
ps.setInt(1,Integer.parseInt(a));
ps.setString(2,b);
ps.setString(3,c);
ps.executeUpdate();
con.commit();
ResultSet rs=st.executeQuery("select * from Dept");
%>
<html><body>
<table border=1>
<tr><th>Dept No </th><th>Dept Name</th><th>Location</th></tr>
<%
while(rs.next())
- 141 -
Siddhesh Kadam TyBsc Advance Java
{
%>
<tr>
<% for(int j=0;j<=2;j++)
{
Object obj=rs.getObject(j+1);
%>
<td><%=obj.toString()%></td>
<%
}
}
%>
</tr>
</table>
<%!
public void jspDestroy()
{ try
{
ps.close();
st.close();
}
catch(Exception e){System.out.println("Error: "+e.getMessage());}
}%>
</body>
</html>
Directives
JSP directives are messages for the JSP engine. They do not directly produce any visible
output, but tell the engine what to do with the rest of the JSP page. JSP directives are
always enclosed within the <%@ ... %> tag. The two primary directives are page and
include.
Page Directive
Typically, the page directive is found at the top of almost all of your JSP pages. There
can be any number of page directives within a JSP page, although the attribute/value pair
must be unique. Unrecognized attributes or values result in a translation error. For
example,
makes available the types declared within the included packages for scripting and sets the
page buffering to 16K.
- 142 -
Siddhesh Kadam TyBsc Advance Java
- 143 -
Siddhesh Kadam TyBsc Advance Java
Include Directive
The include directive lets you separate your content into more manageable elements, such
as those for including a common page header or footer. The page included can be a static
HTML page or more JSP content. For example, the directive:
<%@ include file="copyright.html" %>
can be used to include the contents of the indicated file at any location within the JSP
page.
- 144 -
Siddhesh Kadam TyBsc Advance Java
Declarations
JSP declarations let you define page-level variables to save information or define
supporting methods that the rest of a JSP page may need. While it is easy to get led away
and have a lot of code within your JSP page, this move will eventually turn out to be a
maintenance nightmare. For that reason, and to improve reusability, it is best that logic-
intensive processing is encapsulated as JavaBean components.
Declarations are found within the <%! ... %> tag. Always end variable declarations with
a semicolon, as any content must be valid Java statements:
<%! int i=0; %>
You can also declare methods. For example, you can override the initialization event in
the JSP life cycle by declaring:
<%! public void jspInit() {
//some initialization code
}
%>
Expressions
With expressions in JSP, the results of evaluating the expression are converted to a string
and directly included within the output page. Typically expressions are used to display
simple values of variables or return values by invoking a bean's getter methods. JSP
expressions begin within <%= ... %> tags and do not include semicolons:
<%= fooVariable %>
<%= fooBean.getName() %>
Scriptlets
JSP code fragments or scriptlets are embedded within <% ... %> tags. This Java code is
run when the request is serviced by the JSP page. You can have just about any valid Java
code within a scriptlet, and is not limited to one line of source code. For example, the
following displays the string "Hello" within H1, H2, H3, and H4 tags, combining the use
of expressions and scriptlets:
<% for (int i=1; i<=4; i++) { %>
<H<%=i%>>Hello</H<%=i%>>
<% } %>
Comments
Although you can always include HTML comments in JSP pages, users can view these if
they view the page's source. If you don't want users to be able to see your comments,
embed them within the <%-- ... --%> tag:
<%-- comment for server side only --%>
A most useful feature of JSP comments is that they can be used to selectively block out
scriptlets or tags from compilation. Thus, they can play a significant role during the
debugging and testing process.
Object Scopes
Before we look at JSP syntax and semantics, it is important to understand the scope or
visibility of Java objects within JSP pages that are processing a request. Objects may be
- 145 -
Siddhesh Kadam TyBsc Advance Java
created implicitly using JSP directives, explicitly through actions, or, in rare cases,
directly using scripting code. The instantiated objects can be associated with a scope
attribute defining where there is a reference to the object and when that reference is
removed. The following diagram indicates the various scopes that can be associated with
a newly created object:
- 146 -
Siddhesh Kadam TyBsc Advance Java
Example 4: Write a JSP page that will include in it a simple static file with the help
of <%@ include file=”?” %> and a simple JSP page with the help of <jsp:include
page=”?”/> tag.
Include.jsp
<html>
<body bgcolor="white">
<br>
<H1 align="center">JavaServer Pages 1.0</H1>
<H2 align="center">Include Example</H2>
<P> </P>
<P> </P>
<font color="red">
<p>In place evaluation of another JSP which gives you the current time:
:-)
</html>
foo.jsp
<body bgcolor="white">
<font color="red">
- 147 -
Siddhesh Kadam TyBsc Advance Java
Before you can access a bean within a JSP page, it is necessary to identify the bean and
obtain a reference to it. The <jsp:useBean> tag tries to obtain a reference to an existing
instance using the specified id and scope, as the bean may have been previously created
and placed into the session or application scope from within a different JSP page. The
bean is newly instantiated using the Java class name specified through the class attribute
only if a reference was not obtained from the specified scope. Consider the tag:
In this example, the Person instance is created just once and placed into the session. If
this useBean tag is later encountered within a different JSP page, a reference to the
original instance that was created before is retrieved from the session.
The <jsp:useBean> tag can also optionally include a body, such as
<jsp:useBean id="user" class="beans.Person" scope="session">
<%
user.setDate(DateFormat.getDateInstance().format(new Date()));
/ /etc..
%>
</jsp:useBean>
Any scriptlet (or <jsp:setProperty> tags, which are explained shortly) present within the
body of a <jsp:useBean> tag are executed only when the bean is instantiated, and are
used to initialize the bean's properties.
Once you have declared a JavaBean component, you have access to its properties to
customize it. The value of a bean's property is accessed using the <jsp:getProperty> tag.
With the <jsp:getProperty> tag, you specify the name of the bean to use (from the id field
of useBean), as well as the name of the property whose value you are interested in. The
actual value is then directly printed to the output:
<jsp:getProperty name="user" property="name" />
- 148 -
Siddhesh Kadam TyBsc Advance Java
When developing beans for processing form data, you can follow a common design
pattern by matching the names of the bean properties with the names of the form input
elements. You also need to define the corresponding getter/setter methods for each
property within the bean. The advantage in this is that you can now direct the JSP engine
to parse all the incoming values from the HTML form elements that are part of the
request object, then assign them to their corresponding bean properties with a single
statement, like this:
<jsp:setProperty name="user" property="*"/>
This runtime magic is possible through a process called introspection, which lets a class
expose its properties on request. The introspection is managed by the JSP engine, and
implemented through the Java reflection mechanism. This feature alone can be a lifesaver
when processing complex forms containing a significant number of input elements.
If the names of your bean properties do not match those of the form's input elements, they
can still be mapped explicitly to your property by naming the parameter as:
<jsp:setProperty name="user" property="address" param="parameterName" />
Including Requests
The <jsp:include> tag can be used to redirect the request to any static or dynamic
resource that is in the same context as the calling JSP page. The calling page can also
pass the target resource bean parameters by placing them into the request, as shown in the
diagram:
For example:
<jsp:include page="shoppingcart.jsp" flush="true"/>
not only allows shoppingcart.jsp to access any beans placed within the request using a
<jsp:useBean> tag, but the dynamic content produced by it is inserted into the calling
page at the point where the <jsp:include> tag occurs. The included resource, however,
cannot set any HTTP headers, which precludes it from doing things like setting cookies,
or else an exception is thrown.
- 149 -
Siddhesh Kadam TyBsc Advance Java
Example 5: Create a java bean that gives information about the current time. The
bean has getter properties for time, hour, minute, and second. Write a JSP page
that uses the bean and display all the information.
package myclass;
import java.util.Calendar;
import java.util.Date;
public class CalendarBean
{
private Calendar calendar;
public CalendarBean() {
calendar=Calendar.getInstance();
}
public Date getTime() {
return calendar.getTime();
}
public int getHour() {
return calendar.get(Calendar.HOUR_OF_DAY);
}
public int getMinute() {
return calendar.get(Calendar.MINUTE);
}
public int getSecond() {
return calendar.get(Calendar.SECOND);
}
}
- 150 -