unit - i java swing - vandemataram college · swing development has its roots in the...
Post on 15-Jul-2019
223 Views
Preview:
TRANSCRIPT
www.vandemataramcollege.com Page 1
UNIT - I
JAVA SWING
Swing, which is part of the java Foundation Classes(JFC) library, is an extension of the Abstract
Window Toolkit(AWT) that has been integrated in java 2. It offers much improved functionality
over its predecessor- new components, expanded components features, better event handling
and drag and drop support.
THE JAVA FOUNDATION CLASSES
The AWT was a powerful toolkit when introduced, and it was the original driving force behind
Java`s popularity. Now Swing, which has about four times the number of user interface (UI)
components as the AWT, is part of the standard Java distribution. The AWT component set
wasn`t designed for the popularity that it was received with, and in the context of today`s
programming needs, it`s rather limited in range, has a lot bugs, and takes up a lot of system
resources.
Many programmers think that JFC and Swing are the same thing, but that`s not so; the JFC
contains Swing and quite a number of other items. Here`s what`s in the JFC:
Swing- The large UI package
Cut and Paste- Clipboard support
Accessibility features-Aimed at users with disabilities
The Desktop Colors features-First introduced in Java 1.1
Java 2D-Improved color, image,and text support
Swing introduced three significant advances : it uses fewer system resources, adds a lot
more sophisticated components, and helps to tailor the look and feel of the programs.
JFC TECHNOLOGIES
JFC contains two major technologies, one of which is Swing. JFC also contains the Abstract
Window Toolkit (AWT), Accessibility, Drag and Drop, and 2D Graphics. The following is the brief
description of the constituents of JFC:
Accessibility API- Assistive technologies (or systems) are useful for disabled people who
need additional help to use the user interface. The assistive systems include screen
readers, screen magnifiers, and speech recognition systems.
Abstract Windowing Toolkit- The AWT is new to Java programmers. The AWT is the
cornerstone for the JFC itself and is one of the core libraries that was launched with JDK
1.0. In fact, the AWT lays the foundation for the Swing components. Even though user
www.vandemataramcollege.com Page 2
interfaces can be created using Swing components, the layout managers and event
models supported by AWT has to be used.
2D Graphics- JDK 1.2 has arrived with 2D graphics that enhance the existing graphics
support. The 2D Graphics API can support advanced 2D graphics and imaging.
Drag and Drop- With native platform-capable drag and drop, a user with a native
application sitting next to a Java application will be able to drag and drop between the
Java and native applications.
MVC (Model View Controller)
MVC framework is used to separate the data access layer, business logic code and the graphical user interface that has to be defined and designed to let the user interact with the application. This application has three parts,
1. Model - this part of the framework is to store the data of the application, such as databases, text data, files and/or other web resources.
2. View - this is the graphical user interface of the application. That would contain different buttons, text boxes and other controls to let the user interact with the application to complete his projects depending on sort of the software he is using.
3. Controller - the actual back-end code constitutes the controller of the framework. A controller controls the data coming from the users, or going to the user from a model.
COMPARISON BETWEEN SWING AND AWT
The biggest different between the AWT components and Swing components is that the Swing
components are implemented with absolutely no native code. They have more functionality
than AWT components. Because the Swing components have no native code, they can be
shipped as an add-on to JDK 1.1, in addition to being part of JDK 1.2.
Even the simplest Swing components have capabilities far beyond what the AWT components
offer:
Swing buttons and labels can display images instead of, or in addition to, text.
One can easily add or change the borders drawn around most of the Swing components.
For example , it`s easy to put a box around the outside of a container or label.
Swing components don`t have to be rectangular. Buttons, for example ,can be round.
Assertive technologies such as screen readers can easily get information from Swing
components. For example , a tool can easily get the text that`s displayed on a button or
label.
Swing lets you specify which look and feel your programs GUI uses. By contrast, AWT
components always have the look & feel of the native platform.
www.vandemataramcollege.com Page 3
All elements of Swing are part of the javax. swing package. To use a Swing class, one can
either use an import statement for a specific class to be imported or import all classes
from the Swing package as follows:
Difference between Swing & AWT
Java AWT Java Swing
AWT components are platform-
dependent.
Java swing components are platform-
independent.
AWT components are heavyweight. Swing components are lightweight.
AWT doesn't support pluggable look
and feel.
Swing supports pluggable look and feel.
AWT provides less components than
Swing.
Swing provides more powerful
componentssuch as tables, lists, scrollpanes,
colorchooser, tabbedpane etc.
AWT doesn't follows MVC(Model View
Controller) where model represents data,
view represents presentation and
controller acts as an interface between
model and view.
Swing follows MVC.
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. Example: Write a program to create a Login Screen. //Step 1 – import all the required packages import javax.swing.*; import java.awt.*; //Step 2 – Decide the class name & Container class //(JFrame/JApplet) to be used public class Login extends JFrame { //Step 3 – Create all the instances required JTextField txtName,txtPass; JLabel lblName, lblPass;
www.vandemataramcollege.com Page 4
JButton cmdOk,cmdCancel; public Login() { //Step 4- Create objects for the declared instances txtName=new JTextField(); txtPass =new JTextField(); lblName=new JLabel(“User Name”); lblPass =new JLabel(“Password”); cmdOk =new JButton(“Ok”); cmdCancel=new JButton(“Cancel”); //Step 5 – Add all the objects in the Content Pane with //Layout Container con=getContentPane(); con.setLayout(new FlowLayout()); con.add(lblName); con.add(txtName); con.add(lblPass); con.add(txtPass); con.add(cmdOk); con.add(cmdCancel); }//constructor //Step 6 – Event Handling. (Event handling code will come here) public static void main(String args[]) { //Step 7 – Create object of class in main method Login l=new Login(); l.setSize(150,200); l.setVisible(true); }//main }//class Importing required packages The following line imports the main Swing package: import javax.swing.*; Most Swing programs also need to import the two main AWT packages: import java.awt.*; import java.awt.event.*; Decide the class name & Container class 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. Create all the instances required 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. Adding Components to Containers Every Container has a default layout manger that places the components inside the container according to the available size of the conent pane. In swing we cannot add a component
www.vandemataramcollege.com Page 5
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. Creating object of the class in main method 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(). 1.2 SWING FEATURES AND CONCEPTS
Swing development has its roots in the Model-View-Controller (MVC) architecture. The MVC-
based architecture allows Swing components to be replaced with different data models and
views. The pluggable look and feel is a result of the MVC architecture. Because Java is a
platform-independent language and runs on any client machine, the look and feel of any
platform has to be known. The following is a summary of Swing`s key features:
Lightweight Components- Stating with the JDK 1.1, the AWT supports lightweight
component development. For a component to qualify as lightweight, it cannot depends
on any native system classes. In Swing most of the components have their own view
supported by Java look feel classes.
Pluggable Look and Feel- This feature enables the user to switch the look and feel of
Swing components without restating the application. The Swing library supports a cross-
plate form look and feel also called the Java look and feel that remains the same across
all platforms wherever the program runs. The native look and feel is native to whatever
particular system on which the program happens to be running, including Windows and
Motif. The Swing library provides an API that gives flexibility in determining the look and
feel of the applications.
Swing Components and the Containment Hierarchy – Swing provides many standard GUI components such as buttons, lists, menus, and text areas, which you combine to create your program's GUI. It also includes containers such as windows and tool bars.
Layout Management - Layout management is the process of determining the size and position of components. By default, each container has a layout manager -- an object that performs layout management for the components within the container. Components can provide size and alignment hints to layout managers, but layout managers have the final say on the size and position of those components.
Event Handling - Event handling is how programs respond to external events, such as the user pressing a mouse button. Swing programs perform all their painting and event handling in the event-dispatching thread. Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener
www.vandemataramcollege.com Page 6
on the appropriate event source. Swing components can generate many kinds of events.
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.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
www.vandemataramcollege.com Page 7
1.3 SWING API COMPONENTS – HEAVY WEIGHT CONTAINERS 1.3.1 JFrames A frame, implemented as an instance of the JFrame class, is a window that has decorations such as a border, a title, and buttons for closing and iconifying the window. Applications with a GUI typically use at least one frame. By default, when the user closes a frame onscreen, the frame is hidden. Although invisible, the frame still exists and the program can make it visible again. If you want different behavior, then you need to either register a window listener that handles window-closing events, or you need to specify default close behavior using the setDefaultCloseOperation method. You can even do both. The argument to setDefaultCloseOperation must be one of the following values, which are defined in the WindowConstants interface:
-- Don't do anything when the user's requests that the frame close. Instead, the program should probably use a window listener that performs some other action in its windowClosing method.
-- Hide the frame when the user closes it. This removes the frame from the screen.
-- Hide and dispose of the frame when the user closes it. This removes the frame from the screen and frees up any resources used by it. Constructors: JFrame() JFrame(String) : Create a frame that is initially invisible. Call setVisible(true) :on the frame to make it visible. The String argument provides a title for the frame. You can also use setTitle to set a frame's title. Methods: 1 Container getContentPane() - Returns the contentPane object for this frame. 2 JMenuBar getJMenuBar() - Returns the menubar set on this frame. 3 void setDefaultCloseOperation(int operation) - Sets the operation that will happen by default when the user initiates a "close" on this frame. 4 void setJMenuBar(JMenuBar menubar) - Sets the menubar for this frame. 5 void setVisible(boolean b) - Shows or hides this component depending on the value of parameter b. 6 void setLocation (int x,int y) - Moves this component to a new location. The top-left corner of the new location is specified by the x and y parameters in the coordinate space of this component's parent.
7 void pack() - Causes this Window to be sized to fit the preferred size and layouts of its
subcomponents. If the window and/or its owner are not yet displayable, both are made
displayable before calculating the preferred size. The Window will be validated after the
preferredSize is calculated.
www.vandemataramcollege.com Page 8
8 void setTitle(String title) - Sets the title for this frame to the specified string. Program to demonstrate the concept of JFrame import javax.swing.*; import java.awt.*; import java.awt.event.*;
public class app extends JFrame
{
JLabel jl;
public app()
{
super("Swing application with Frame");
Container contentPane = getContentPane();
jl = new JLabel("Hello from Swing");
contentPane.add(jl);
}
public static void main(String args[])
{
JFrame f = new app();
f.setBounds(100,100,300,300);
f.setVisible(true);
f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}}
1.3.2 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. Dialogs can alos be used for information messages or warnings. Dialogs are defined by the JDialog class in the javax.swing package and a JDialog object is a specialized sort of a window. There are two kinds of dialogs boxes. i.e Modal and Non Modal dialog. Modal dialog :when a modal dialog is displayed by selecting a menu item or clicking a button it inhibits the operation of any other window in the application until dialog is closed. It manages input normally have at least two buttons an ok button to accept input and cancel button is used to close the dialog.
www.vandemataramcollege.com Page 9
Non-modal dialog : A non modal dialog can be left on the screen as long as needed, since it doesn’t block the interaction with other windows in the application. Constructors : 1 JDialog(Frame owner) Creates a non-modal dialog without a title with the specifed Frame as its owner. 2 JDialog(Frame owner, String title, boolean modal) : Creates a modal or non-modal dialog with the specified title and the specified owner Frame. Methods: 1 protected void dialogInit() - Called by the constructors to init the JDialog properly. 2 Container getContentPane() - Returns the contentPane object for this dialog. 3 void setDefaultCloseOperation(int operation) - Sets the operation which will happen by default when the user initiates a "close" on this dialog. 4 void setLayout(LayoutManager manager) - By default the layout of this component may not be set, the layout of its contentPane should be set instead. 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. 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)
Program to demonstrate the concept of JApplet import javax.swing.*; import java.awt.*; import java.awt.event.*;
//<applet code=appletdemo height=300 width=300></applet>
public class appletdemo extends JApplet
{
Public void init()
{
Container c=getContentPane();
www.vandemataramcollege.com Page 10
JLabel jl=new JLabel(“This is a swing Applet”, new
ImageIcon(“Sunset.jpg”),JLabel.CENTER);
c.add(jl);
}
}
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: 1 JWindow() - Creates a window with no specified owner. 2 JWindow(Frame owner) - Creates a window with the specified owner frame. 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. Program to demonstrate the concept of JWindow
www.vandemataramcollege.com Page 11
1.4 SWING API COMPONENTS - TOP-LEVEL CONTAINERS Swing provides three generally useful top-level container classes: JFrame JDialog, and JApplet. To appear onscreen, every GUI component must be part of a containment hierarchy. Each containment hierarchy has a top-level container as its root. Each top-level container has a content pane. Top-Level Containers and Containment Hierarchies 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. Adding Components to the Content Pane 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); Adding a Menu Bar : 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); The Root Pane 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. The two other components that a root pane adds are a layered pane and a glass pane. 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.
www.vandemataramcollege.com Page 12
JRootPane's layeredPane The layeredPane is the parent of all children in the JRootPane. It is an instance of JLayeredPane, which provides the ability to add components at several layers. This capability is very useful when working with popup menus, dialog boxes, and dragging -- situations in which you need to place a component on top of all other components in the pane. 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. 1.5 SWING API COMPONENTS – INTERMEDIATE SWING CONTAINERS 1.5.1 JPanel : JPanel is a generic lightweight container. JPanel is the most flexible, frequently used intermediate container. Implemented with the JPanel class, panels add almost no functionality beyond what all JComponent objects have. They are often used to group components, whether because the components are related or just because grouping them makes layout easier. A panel can use any layout manager, and you can easily give it a border. The content panes of top-level containers are often implemented as JPanel instances. 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 :
1. JPanel() 2. JPanel(LayoutManager) : Create a panel. The LayoutManager parameter provides a
layout manager for the new panel. By default, a panel uses a FlowLayout to lay out its components.
Methods :
www.vandemataramcollege.com Page 13
1. void add(Component) 2. void add(Component, int) 3. void add(Component, Object) 4. void add(Component, Object, int)
5. void remove(Component) 6. void remove(int) 7. void removeAll(): Remove the specified component(s). 8. void setLayout(LayoutManager) 9. LayoutManager getLayout() : Set or get the layout manager for this panel. The layout manager is responsible for positioning the panel's components within the panel's bounds according to some philosophy.
A swing program to demonstrate the concept of JPanel :-
import java.awt.*; import javax.swing.*;
//<applet cde=applet width=300 height=300></applet>
public class appletdemo extends JApplet
{
jpanel j;
public void init()
{
Container contentPane=getContentPane();
j=new jpanel();
contentPane.add(j);
}
}
class jpanel extends JPanel
{
jpanel()
{
setBackground(Color.white);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("Hello from Swing!",0,60);
}
}
1.5.2 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. Constructors :
www.vandemataramcollege.com Page 14
1. JScrollPane() 2. JScrollPane(Component) 3. JScrollPane(int, int) 4. JScrollPane(Component,int, int) : Create a scroll pane. The Component parameter, when
present, sets the scroll pane's client. The two int parameters, when present, set the vertical and horizontal scroll bar policies (respectively).
1.5.3 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 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. Method Purpose
1. void setVerticalScrollBarPolicy(int) : 2. int getVerticalScrollBarPolicy() (SAME FOR HORIZONTAL) Set or get the vertical scroll
policy. ScrollPaneConstants defines three values for specifying this policy: VERTICAL_SCROLLBAR_AS_NEEDED (the default), VERTICAL_SCROLLBAR_ALWAYS, and VERTICAL_SCROLLBAR_NEVER.
3. void setViewportBorder(Border): 4. Border getViewportBorder() : Set or get the border around the viewport. 5. Void setColumnHeaderView(Component) : 6. Void setRowHeaderView(Component) : Set the column or row header for the scrollpane. 7. void setCorner(Component, int) 8. Component getCorner(int) : Set or get the corner specified.
The int parameter 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. Constructors:
1. JTabbedPane() 2. JTabbedPane(int tabPlacement) 3. JTabbedPane(int tabPlacement, 4. int tabLayoutPolicy)
Creates a tabbed pane. The first optional argument specifies where the tabs should appear. By default, the tabs appear at the top of the tabbed pane.You can specify these positions TOP, BOTTOM, LEFT, RIGHT. The second optional argument specifies the tab layout policy. Methods:
1. JTabbedPane() 2. JTabbedPane(int) :Create a tabbed pane. The optional argument 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.
3. addTab(String, Icon,Component, String)
www.vandemataramcollege.com Page 15
4. addTab(String, Icon,Component) 5. addTab(String,Component) : Add a new tab to the tabbed pane. The first argument
specifies the text on the tab. The optional icon argument specifies the tab's icon. The component argument specifies the component that the tabbed pane should show when the tab is selected.
6. insertTab(String, Icon, Component, String, int): Insert a tab at the specified index, where the first tab is at index 0. The arguments are thesame as for addTab.
Example: Demo example to use JTabbedPane. Create a tabbed pane and add three tabs using JPanel class. import javax.swing.*; /*<applet code="TabbedPaneDemo.class" height=500 width=500></applet> */ public class TabbedPaneDemo extends JApplet { public void init() { JTabbedPane jtp=new JTabbedPane(); jtp.addTab("Cities",new CitiesPanel()); jtp.addTab("Color",new ColorPanel()); jtp.addTab("Flavour",new FlavourPanel()); getContentPane().add(jtp); } } class CitiesPanel extends JPanel { public CitiesPanel() { add(new JButton("Mumbai")); add(new JButton("Delhi")); add(new JButton("Banglore")); add(new JButton("Chennai")); } } class ColorPanel extends JPanel { public ColorPanel() { add(new JCheckBox("Red")); add(new JCheckBox("Yellow")); add(new JCheckBox("Green")); add(new JCheckBox("Blue")); } } class FlavourPanel extends JPanel { public FlavourPanel() { String item[]={"Vanila","Stroberry","Chocolet"}; JComboBox jcb=new JComboBox(item); add(jcb); } } 1.6 SWING API COMPONENTS - 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.
www.vandemataramcollege.com Page 16
Rules of Using Internal Frames - If you don't set the size of the internal frame, it
will have zero size and thus never be visible. You can set the size using one of the following methods: setSize, pack, or setBounds.
rule, you should set the location of the internal frame – If you don't set the location of the internal frame, it will come up at 0,0 (the upper left of its container). You can use the setLocation or setBounds method to specify the upper left point of the internal frame, relative to its container. internal frame's content pane.
- If you don't add the internal frame to a container (usually a JDesktopPane), the internal frame won't appear.
Constructors:
1. JInternalFrame() - Creates a non-resizable, non-closable, nonmaximizable, non-iconifiable JInternalFrame with no title.
2. JInternalFrame(String title, boolean resizable, boolean closable) -Creates a non-maximizable, non-iconifiable JInternalFrame with thespecified title, resizability, and closability.
Methods: 1. Void setVisible(boolean) : Make the internal frame visible (if true) or invisible (if false).
You should invoke setVisible(true) on each JInternalFrame before adding it to its container. (Inherited from Component).
2. void pack () Size the internal frame so that its components are at their preferred sizes. 3. void setLocation(Point) 4. void setLocation(int, int) : Set the position of the internal frame.(Inherited from
Component). 5. Void setBounds(Rectangle) 6. void setBounds(int, int, int, int) : Explicitly set the size and location of the internal
frame. (Inherited from Component). 7. Void setSize(Dimension) 8. void setSize(int, int) : Explicitly set the size of the internal frame.(Inherited from
Component). 9. void set Closed (boolean) 10. boolean is Closed() : Set or get whether the internal frame is currently closed. The
argument to setClosed must be true. When reopening a closed internal frame, you make it visible
11. and add it to a container (usually the desktop pane you originally added it to).
www.vandemataramcollege.com Page 17
Example: Demo example to use internal frames. Create three internal frames and add them to the main frame. //First internal frame import javax.swing.*; import java.awt.Dimension; public class CitiesPanel extends JInternalFrame { public CitiesPanel() { super("Select Cities",true,true); JPanel jp=new JPanel(); jp.add(new JButton("Mumbai")); jp.add(new JButton("Pune")); jp.add(new JButton("Kolkata")); getContentPane().add(jp); setPreferredSize(new Dimension(300,300)); setDefaultCloseOperation(HIDE_ON_CLOSE); } } //Second internal frame import javax.swing.*; import java.awt.Dimension; public class ColorPanel extends JInternalFrame { public ColorPanel() { super("Select Colors",true,true); JPanel jp=new JPanel(); jp.add(new JButton("Red")); jp.add(new JButton("Blue")); jp.add(new JButton("Green")); getContentPane().add(jp); setPreferredSize(new Dimension(300,300)); setDefaultCloseOperation(HIDE_ON_CLOSE); } } //Third internal frame import javax.swing.*; import java.awt.Dimension; public class FlavourPanel extends JInternalFrame { public FlavourPanel() { super("Select Flavours",true,true);
www.vandemataramcollege.com Page 18
JPanel jp=new JPanel(); jp.add(new JButton("Vanilla")); jp.add(new JButton("Chocolate")); jp.add(new JButton("Strawberry")); getContentPane().add(jp); setPreferredSize(new Dimension(300,300)); setDefaultCloseOperation(HIDE_ON_CLOSE); } } //Main Frame import java.awt.*; import java.awt.event.*; import javax.swing.*; public class IFrameDemo extends JFrame implements ActionListener { CitiesPanel c1=new CitiesPanel(); ColorPanel c2=new ColorPanel(); FlavourPanel c3=new FlavourPanel(); public IFrameDemo() { JMenuBar mb=new JMenuBar(); JMenu select=new JMenu("Select"); JMenuItem city=new JMenuItem("City"); JMenuItem color=new JMenuItem("Color"); JMenuItem flavour=new JMenuItem("Flavour"); select.add(city); select.add(color); select.add(flavour); mb.add(select); setJMenuBar(mb); city.addActionListener(this); color.addActionListener(this); flavour.addActionListener(this); JDesktopPane dp=new JDesktopPane(); dp.setLayout(new FlowLayout()); dp.add(c1); dp.add(c2); dp.add(c3); getContentPane().add(dp,BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String args=e.getActionCommand();
www.vandemataramcollege.com Page 19
if(args.equals("City")) { c1.setVisible(true); c2.setVisible(false); c3.setVisible(false); } else if(args.equals("Color")) { c1.setVisible(false); c2.setVisible(true); c3.setVisible(false); } else if(args.equals("Flavour")) { c1.setVisible(false); c2.setVisible(false); c3.setVisible(true); } } public static void main(String args[]) { IFrameDemo f1=new IFrameDemo(); f1.setVisible(true); f1.setSize(500,500); f1.setTitle("Internal Frame Demo"); f1.setDefaultCloseOperation(EXIT_ON_CLOSE); } }
The objective of this chapter is to lear how to use the Swing Components to create a user interface. We will start the chapter with a few components and then lear how to incorporate the Java Print API. 2.1 THE JCOMPONENT CLASS With the exception of top-level containers, all Swing components whose names begin with "J" descend from the JComponent class. For example, JLabel, JButton, JTree, and JTable all inherit from JComponent. However, JFrame doesn't because it implements a top-level container. 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. 2.1.2 JLabel
www.vandemataramcollege.com Page 20
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. Constructor :
1. JLabel(Icon) 2. JLabel(Icon, int) 3. JLabel(String) 4. JLabel(String, Icon, int) 5. JLabel(String, int) 6. JLabel()
Creates a JLabel instance, initializing it to have the specified text/image/alignment. The int argument specifies the horizontal alignment of the label's contents within its drawing area. The horizontal alignment must be one of the following constants defined in the SwingConstants interface (which JLabel implements): LEFT, CENTER, RIGHT, LEADING, or TRAILING. For ease of localization, we strongly recommend using LEADING and TRAILING, rather than LEFT and RIGHT.
1. void setText(String) 2. String getText() : Sets or gets the text displayed by the label. 3. void setIcon(Icon) 4. Icon getIcon() : Sets or gets the image displayed by the label. 5. Void setDisplayedMnemonicIndex(int) 6. Int getDisplayedMnemonicIndex() : Sets or gets a hint as to which character in the text
should be decorated to represent the mnemonic. This is useful when you have two instances of the same character and wish to decorate the second instance.
7. setDisplayedMnemonicIndex(5) : Decorates the character that is at position 5 (that is, the 6th character in the text). Not all types of look and feel may support this feature.
8. void setDisabledIcon(Icon) 9. Icon getDisabledIcon() : Sets or gets the image displayed by the label when it is disabled.
If you do not specify a disabled image, then the look and feel creates one by manipulating the default image.
2.1.4 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. Constructor
1. JButton(Action) Create a JButton instance, initializing it to 2. JButton(String, Icon) 3. JButton(String) 4. JButton(Icon) 5. JButton() : have the specified text/image/action.
Methods 1. void setAction(Action)
www.vandemataramcollege.com Page 21
2. Action getAction() : Set or get the button's properties according to values from the Action instance.
3. void setText(String) 4. String getText() : Set or get the text displayed by the button. 5. void setIcon(Icon) : 6. Icon getIcon() : Set or get the image displayed by the button when the button isn't
selected or pressed.
A Swing Program for JButton with image:-
import java.awt.*; import javax.swing.*; import java.awt.event.*;
//<applet code=button width=300 height=300> </applet>
public class imagebutton extends JApplet implements ActionListener
{
JButton button=new JButton("Button",new ImageIcon("yyy.gif"));// use / or place
image in bin
JTextField text=new JTextField(20);
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
contentPane.add(text);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{ text.setText("Hello");
}
}
Using Text Entry Components Swing text components display text and optionally allow the user to edit the text. Programs need text components for tasks ranging from the straightforward (enter a word and press Enter). Swing provides six text components, along with supporting classes and interfaces that meet even the most complex text requirements. In spite of their different uses and capabilities, all Swing text components inherit from the same superclass, The following figure shows the JTextComponent hierarchy. .
www.vandemataramcollege.com Page 22
2.1.3 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. Method or Constructor Purpose
1. JTextField() 2. JTextField(String) 3. JTextField(String, int) 4. JTextField(int): Creates a text field. When present, the int argument specifies the desired
width in columns. The String argument contains the field's initial text. 5. void setText(String) 6. String getText() :Sets or obtains the text displayed by the text field. 7. void setEditable(boolean) 8. boolean isEditable() : Sets or indicates whether the user can edit the text in the text
field. 9. void setColumns(int) 10. int getColumns() : Sets or obtains the number of columns displayed by the text field.
This is really just a hint for computing the field's preferred width. 11. Void setHorizontalAlignment(int) 12. Int getHorizontalAlignment() :Sets or obtains how the text is aligned horizontally
within its area. You can use JTextField.LEADING, JTextField.CENTER, and TextField.TRAILING for arguments.
The usual way to add a text field to a window is to add it to a panel or other container—just as
you would a button:
JPanel p = new JPanel();
www.vandemataramcollege.com Page 23
JTextField tf1 = new JTextField("Default input", 20);
p.add(tf1);
To make a blank text field, just leave out the string as a parameter for the JTextField constructor:
JTextField textField = new JTextField(20);
You can change the contents of the text field at any time by using the setText method from
the TextComponent parent class mentioned in the previous section. For example:
textField.setText("Hello!");
JPasswordField : JPasswordField (a direct subclass of JTextField) you can suppress the
display of input. Each character entered can be replaced by an echo character. This allows
confidential input for passwords, for example. By default, the echo character is the asterisk, *.
When the user types data into them and presses the Enter key, an action event occurs. If the
program registers an event listener, the listener processes the event and can use the data in the
text field at the time of the event in the program. If you need to provide an editable text field that
doesn’t show the characters the user types – use the JPasswordField class.To create
JPasswordField use following statement
JPasswordField psw= new JPasswordField ();
Output
JPasswordField Constructor
1. JPasswordField() : Constructs a new JPasswordField, with a default document, null
starting text string, and 0 column width.
2. JPasswordField(Document doc, String txt, int columns) : Constructs a new
JPasswordField that uses the given text storage model and the given number of columns.
3. JPasswordField(int columns) :Constructs a new empty JPasswordField with the specified
number of columns.
4. JPasswordField(String text): Constructs a new JPasswordField initialized with the
specified text.
5. JPasswordField(String text, int columns) : Constructs a new JPasswordField initialized
with the specified text and columns.
JTextArea: A text area is a text control that lets the user enter multiple lines of text. JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with
class JScrollPane to achieve scrolling. Text areas are implemented in Swing wih the JTextArea class. It takes the following constructor methods.
www.vandemataramcollege.com Page 24
JTextArea Constructor
JTextArea() : Constructs a new TextArea.
JTextArea(int rows, int columns) : Constructs a new empty TextArea with the specified
number of rows and columns.
JTextArea(String text) : Constructs a new TextArea with the specified text displayed.
JTextArea(String text, int rows, int columns): Constructs a new TextArea with the specified
text and number of rows and columns.
JTextArea Methods :
JTextArea(int,int):A text area with the specified number of rows and columns.
JTextArea(String,int,int):A ext area with he specified text,rows,and columns.
Example:
The following example creates a text area object of 10 rows and 20 columns.
JTexArea taRemarks=new JTextArea(10,20);
The following table describes some of the methods provided by the JTextArea class.
Methods Description
Append(String) Appends the given string to the end of the document.
void getColumns(int)
int getRows(int)
Returns the number of columns & rows in the text area.
Insert(String,int) Inserts a specified text at the specified position in the
text area.
void setRows(int)
void setFont(Font)
The setRows() method sets he number of rows for the
text area.
The setFont() method sets a specific font for the text.
JFormattedTextField :
www.vandemataramcollege.com Page 25
2.1.5 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
1. JCheckBox(String) 2. JCheckBox(String, boolean) 3. JCheckBox(Icon) 4. JCheckBox(Icon, boolean) 5. JCheckBox(String, Icon) 6. JCheckBox(String, Icon, boolean) 7. JCheckBox() : Create a JCheckBox instance. The string argument specifies the text, if
any, that the check box should display. Similarly, the Icon argument specifies the image that should be used instead of the look and feel's default check box image. Specifying the boolean argument as true initializes the check box to be 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. Methods
1. String getText() Returns the button's text. 2. boolean isSelected() Returns the state of the button. 3. void setEnabled(boolean b) Enables (or disables) the button. 4. void setSelected(boolean b) Sets the state of the button. 5. void setText(String text) Sets the button's text.
2.1.6 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
1. JRadioButton(String) 2. JRadioButton(String, boolean) 3. JRadioButton(Icon) 4. JRadioButton(Icon, boolean) 5. JRadioButton(String, Icon) 6. JRadioButton(String, Icon, boolean) 7. JRadioButton() : Create a JRadioButton instance. The string argument specifies the text,
if any, that the radio button should display. Similarly, the Icon argument specifies the image that should be used instead of the look and feel's default radio button image. Specifying the boolean argument as true initializes the radio button to be selected, subject to the approval of the ButtonGroup object. If the Boolean argument is absent or false, then the radio button is initially unselected.
Methods same as JCheckBox
www.vandemataramcollege.com Page 26
Example: Write a program to create a user interface for students biodata. (Demo example for JCheckbox, JRadioButton). //Step 1 – import all the required packages import javax.swing.*; import java.awt.*; /* Step 2 – Decide the class name & Container class (JFrame/JApplet) to be used */ public class StudentBioData02 extends JFrame { //Step 3 – Create all the instances required JLabel lbllang,lblstream; JCheckBox cbeng,cbhin,cbmar; JRadioButton rbart,rbcomm,rbsci; ButtonGroup bg; public StudentBioData02() { //Step 4- Create objects for the declared instances lbllang=new JLabel("Languages Known"); lblstream=new JLabel("Stream"); cbeng=new JCheckBox("English",true); cbhin=new JCheckBox("Hindi"); cbmar=new JCheckBox("Marathi"); rbart=new JRadioButton("Arts"); rbcomm=new JRadioButton("Commerce"); rbsci=new JRadioButton("Science"); bg=new ButtonGroup(); bg.add(rbart); bg.add(rbcomm); bg.add(rbsci); //Step 5 – Add all the objects in the Content Pane with Layout Container con=getContentPane(); con.setLayout(new FlowLayout()); con.add(lbllang); con.add(cbeng); con.add(cbhin); con.add(cbmar); con.add(lblstream); con.add(rbart); con.add(rbcomm);con.add(rbsci); }//constructor //Step 6 – Event Handling. (Event handling code will come here) public static void main(String args[]) { //Step 7 – Create object of class in main method StudentBioData02 sbd=new StudentBioData02(); sbd.setSize(150,200); sbd.setVisible(true); }//main
www.vandemataramcollege.com Page 27
}//class 2.1.7 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. Constructors & Method Purpose
1. JComboBox() 2. JComboBox(Object[]) 3. JComboBox(Vector) : Create a combo box with the specified items in its menu. A combo
box created with the default constructor has no items in the menu initially. Each of the other constructors initializes the menu from its argument: a model object, an array of objects, or a Vector of objects.
Methods : 1. void addItem(Object) 2. void insertItemAt(Object, int) : Add or insert the specified object into the combo box's
menu. The insert method places the specified object at the specified index, thus inserting it before the object currently at that index. These methods require that the combo box's data model be an instance of MutableComboBoxModel.
3. Object getItemAt(int) 4. Object getSelectedItem() : Get an item from the combo box's menu. 5. void removeAllItems() 6. void removeItemAt(int) 7. void removeItem(Object) : Remove one or more items from the combo box's menu.
These methods require that the combo box's data model be an instance of MutableComboBoxModel.
8. int getItemCount() Get the number of items in the combo box's menu. 9. Void addActionListener(ActionListener) : Add an action listener to the combo box. The
listener's actionPerformed method is called when the user selects an item from the combo box's menu or, in an editable combo box, when the user presses Enter.
10. Void addItemListener(ItemListener) : Add an item listener to the combo box. The listener's itemStateChanged method is called when the selection state of any of the combo box's items change. 2.1.8 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. Constructor Purpose
1. JList(Object[]) 2. JList(Vector)
www.vandemataramcollege.com Page 28
3. JList() : Create a list with the initial list items specified. The second and third constructors implicitly create an immutable ListModel; you should not subsequently modify the passed-in array or Vector.
Methods 1. void setListData(Object[]) 2. void setListData(Vector) : Set the items in the list. These methods implicitly create an
immutable ListModel. 3. Void setVisibleRowCount(int) 4. int getVisibleRowCount() : Set or get the visibleRowCount property. For a VERTICAL
layout orientation, this sets or gets the preferred number of rows to display without requiring scrolling. For the HORIZONTAL_WRAP or VERTICAL_WRAP layout orientations, it defines how the cells wrap. The default value of this property is VERTICAL.
5. void setSelectionMode(int) 6. int getSelectionMode() : Set or get the selection mode. Acceptable values are:
SINGLE_SELECTION, SINGLE_INTERVAL_SELECTION, or MULTIPLE_INTERVAL_SELECTION (the default), which are defined in ListSelectionModel.
7. Int getAnchorSelectionIndex() 8. Int getLeadSelectionIndex() 9. int getSelectedIndex() 10. int getMinSelectionIndex() 11. int getMaxSelectionIndex() 12. int[] getSelectedIndices() 13. Object getSelectedValue() 14. Object[] getSelectedValues() : Get information about the current selection as indicated.
Example: A Java program to create a user interface for students biodata. (Demo example for JComboBox, JList). //Step 1 – import all the required packages import javax.swing.*; import java.awt.*; /* Step 2 – Decide the class name & Container class (JFrame/JApplet) to be used */ public class StudentBioData03 extends JFrame { //Step 3 – Create all the instances required JLabel lblplang,lblyear; JList lst; JComboBox jcb; public StudentBioData03() { //Step 4- Create objects for the declared instances lblplang=new JLabel("Programming Lang."); lblyear=new JLabel("Academic Year"); Object obj[]={"C","C++","C#","Java"}; lst=new JList(obj);
www.vandemataramcollege.com Page 29
jcb=new JComboBox(); jcb.addItem("First Year"); jcb.addItem("Second Year"); jcb.addItem("Third Year"); //Step 5 – Add all the objects in the Content Pane with Layout Container con=getContentPane(); con.setLayout(new FlowLayout()); con.add(lblplang); con.add(lst); con.add(lblyear); con.add(jcb); }//constructor //Step 6 – Event Handling. (Event handling code will come here) public static void main(String args[]) { //Step 7 – Create object of class in main method StudentBioData03 sbd=new StudentBioData03(); sbd.setSize(150,200); sbd.setVisible(true); }//main }//class 2.1.9 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. In essence, a menu is a button with an associated JPopupMenu. When the "button" is pressed, the JPopupMenu appears. If the "button" is on the JMenuBar, the menu is a top-level window. If the "button" is another menu item, then the JPopupMenu is "pull-right" menu. 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. Constructor
1. JMenuBar() Creates a menu bar. 2. JMenu() 3. JMenu(String) : Creates a menu. The string specifies the text to display for the menu. 4. JMenuItem() 5. JMenuItem(String)
www.vandemataramcollege.com Page 30
6. JMenuItem(Icon) 7. JMenuItem(String, Icon) 8. JMenuItem(String, int) : Creates an ordinary menu item. The icon argument, if present,
specifies the icon that the menu item should display. Similarly, the string argument specifies the text that the menu item should display. The integer argument specifies the keyboard mnemonic to use. Methods :
1. JMenuItem add(JMenuItem) 2. JMenuItem add(String) : Adds a menu item to the current end of the popup menu. If the 3. argument is a string, then the menu automatically creates a JMenuItem object that
displays the specified text. 4. JMenu add(JMenu) Creates a menu bar. 5. void setJMenuBar(JMenuBar) 6. JMenuBar getJMenuBar() : Sets or gets the menu bar of an applet, dialog, frame,
internal frame, or root pane. 7. void setEnabled(boolean) If the argument is true, enable the menu item. Otherwise,
disable the menu item. 8. void setMnemonic(int) Set the mnemonic that enables keyboard navigation to the menu
or menu item. Use one of the VK constants defined in the KeyEvent class. 9. void setAccelerator(KeyStroke) Set the accelerator that activates the menu item. 10. Void addActionListener(ActionListener) 11. Void addItemListener(ItemListener) : Add an event listener to the menu item. See
Handling Events from Menu Items for details. A swing program to demonstrate the concept of JMenuBar:-
import java.awt.*; import javax.swing.*; import java.awt.event.*;
public class menu extends JApplet
{
public void init()
{
JMenuBar bar=new JMenuBar();
JMenu fmenu=new JMenu ("file");
JMenuItem f1=new JMenuItem("New");
JMenuItem f2=new JMenuItem("OPen");
JMenuItem f3=new JMenuItem("Close");
fmenu.add(f1); fmenu.add(f2); fmenu.add(f3);
bar.add(fmenu);
JMenu emenu=new JMenu("Edit");
JMenuItem e1=new JMenuItem("Cut");
JMenuItem e2=new JMenuItem("Copy");
JMenuItem e3=new JMenuItem("Paste");
www.vandemataramcollege.com Page 31
emenu.add(e1); emenu.add(e2); emenu.add(e3);
bar.add(emenu);
setJMenuBar(bar);
}
}
2.1.10 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. Constructors
1. JTable() Constructs a default JTable that is initialized with a default data model, a default column model, and a default selection model.
2. JTable(int numRows, int numColumns) : Constructs a JTable with numRows and numColumns of empty cells using DefaultTableModel.
3. JTable(Object[][] rowData, Object[] columnNames) Constructs a JTable to display the values in the two dimensional array, rowData, with column names, columnNames.
4. JTable(Vector rowData, Vector columnNames) : Constructs a JTable to display the values in the Vector of Vectors, rowData, with column names, columnNames.
Methods 1. void clearSelection() Deselects all selected columns and rows. 2. int getColumnCount() Returns the number of columns in the column model. 3. String getColumnName(int column) : Returns the name of the column appearing
in the view at column position column. 4. int getRowCount() Returns the number of rows in this table's model. 5. int getRowHeight() Returns the height of a table row, in pixels. 6. int getSelectedColumn() Returns the index of the first selected column, -1 if no
column is selected. 7. int getSelectedRow() Returns the index of the first selected row, -1 if no row is
selected. 8. Object getValueAt(int row, int column) : Returns the cell value at row and column. 9. void selectAll() Selects all rows, columns, and cells in the table. 10. Void setValueAt(Object aValue, int row, int column) : Sets the value for the cell in
the table model at row and column. Table Header : Table header is the top portion of each columns in a table where the column title is displayed. In swing the column header is represented by the class JTableHeader. There is another method called getDefaultTableHeader when no other header has been assigned. A difference table header can be assigned by using the class setTableHeader()
www.vandemataramcollege.com Page 32
Resizing Columns : By default the tables created in swing allow resizing of columns. The width of a columns. The width of a column can be adjusted by dragging the mouse on a column line. Example: Write a program to create a user interface for students biodata. (Demo example for JTable, JScrollPane). //Step 1 – import all the required packages import javax.swing.*; import java.awt.*; /* Step 2 – Decide the class name & Container class (JFrame/JApplet) to be used */ public class StudentBioData04 extends JFrame { //Step 3 – Create all the instances required JLabel lbldata; JTable tbldata; JScrollPane jsp; public StudentBioData04() { //Step 4- Create objects for the declared instances lbldata=new JLabel("Educational Details"); Object header[]={"Year","Degree","Class"}; Object rowdata[][]={ {"2005","SSC","First"}, {"2007","HSC","Second"}, {"2011","BSc","Distinction"} }; tbldata=new JTable(rowdata,header); jsp=new JScrollPane(tbldata); //Step 5 – Add all the objects in the Content Pane with Layout Container con=getContentPane(); con.setLayout(new FlowLayout()); con.add(lbldata); con.add(jsp); }//constructor //Step 6 – Event Handling. (Event handling code will come here) public static void main(String args[]) { //Step 7 – Create object of class in main method StudentBioData04 sbd=new StudentBioData04(); sbd.setSize(150,200); sbd.setVisible(true); }//main}//class 2.1.11 JTree A JTree is a component that displays information in a hierarchical format. Steps for creating a JTree are as follows:
www.vandemataramcollege.com Page 33
bjects for all the nodes required with the help of DefaultMutableTreeNode, which implemets Mutable TreeNode interface which extends the TreeNode interface. The TreeNode interface declares methods that obtains information about aTreeNode. To create a heirarchy of TreeNodes the add() of the DefaultMutableTreeNode can be used. Methods of TreeNode interface
1. TreeNode getChildAt(int childIndex): Returns the child TreeNode at index childIndex.
2. int getChildCount() Returns the number of children TreeNodes the receiver contains.
3. Int getIndex(TreeNode node) : Returns the index of node in the receivers children.
4. TreeNode getParent() Returns the parent TreeNode of the receiver. Methods of MutuableTreeNode
1. Void insert(MutableTreeNode child, int index) : Adds child to the receiver at index.
2. void remove(int index) Removes the child at index from the receiver. 3. void remove (MutableTreeNode node) : Removes node from the receiver. 4. void setParent (MutableTreeNode newParent) : Sets the parent of the receiver to
newParent. Methods of DefaultMutableTreeNode
1. void add (MutableTreeNode newChild) : Removes newChild from its parent and makes it a child of this node by adding it to the end of this node's child array.
2. int getChildCount() Returns the number of children of this node. 3. TreeNode[] getPath() Returns the path from the root, to get to this node. 4. TreeNode getRoot() Returns the root of the tree that contains this node. 5. 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.
scroll pane to the
content pane. Example: Demo example for tree. import java.awt.*; import javax.swing.*; import javax.swing.tree.*; import java.awt.event.*; //<applet code="TreeDemo" height=150 width=120></applet> public class TreeDemo extends JApplet { JTree tree; JTextField txt1; public void init()
www.vandemataramcollege.com Page 34
{ Container con=getContentPane(); con.setLayout(new BorderLayout()); DefaultMutableTreeNode top=new DefaultMutableTreeNode("Option"); DefaultMutableTreeNode stream=new DefaultMutableTreeNode("Stream"); DefaultMutableTreeNode arts=new DefaultMutableTreeNode("Arts"); DefaultMutableTreeNode science=new DefaultMutableTreeNode("Science"); DefaultMutableTreeNode comm=new DefaultMutableTreeNode("Commerce"); DefaultMutableTreeNode year=new DefaultMutableTreeNode("Year"); DefaultMutableTreeNode fy=new DefaultMutableTreeNode("FY"); DefaultMutableTreeNode sy=new DefaultMutableTreeNode("SY"); DefaultMutableTreeNode ty=new DefaultMutableTreeNode("TY"); 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); JScrollPane jsp=new JScrollPane( tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); con.add(jsp,BorderLayout.CENTER); txt1=new JTextField("",20); con.add(txt1,BorderLayout.SOUTH); tree.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent me) { doMouseClicked(me); } }); }// init() void doMouseClicked(MouseEvent me) { TreePath tp=tree.getPathForLocation(me.getX(),me.getY()); if(tp!=null) { txt1.setText(tp.toString()); } else { txt1.setText(""); } }//doMouse }//class
2.1.13 JProgressBar: Progress bars are components used when long tasks are performed to show the user how much time is left before the task is complete. The
www.vandemataramcollege.com Page 35
progress of the task can be represented numerically. Progress bars are created by specifying minimum and maximum values. Constructors :
1. JProgressBar() : Creates a new Progress bar 2. JProgressBar(int,int) : Creates a new Progress bar with the specified minimum
value and maximum value. 3. JProgressBar(int,int,int) : Creates a new Progress bar with the specified
orientation, minimum value and maximum value. The orientation of the Progress bar can be established with the SwingConstants.VERTICAL and SwingConstants.HORIZONTAL class variables. Progress bars are horizontal by default. The minimum and amaximum values can alos be set up by calling the progress bars setMinimum(int) and setMaximum(int) methods with the appropriate values. To update a Progress bar one can call the setValue(int) method with the value indicating how far along the task is at the moment. A swing program to demonstrate the concept of JProgressBar
import java.awt.*; import javax.swing.*; import java.awt.event.*; //<applet code=progressbar width=400 height=400></applet> public class progressbar extends JApplet implements ActionListener { JButton b1=new JButton("Increment value"); JProgressBar jbar=new JProgressBar(); JFrame frame=new JFrame("process bar frame"); JPanel panel=new JPanel(); public void init() { panel.add(jbar); panel.add(b1); frame.add(panel); jbar.setStringPainted(true); frame.setSize(250,200); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { jbar.setValue(jbar.getValue()+20); } }
www.vandemataramcollege.com Page 36
2.1.14 JSlider : JSlider that are implemented in swing through the JSlider
classenables a number to beset sliding a control within the range of a minimum and maximum values. In many cases, a slider can be used for numeric input instead of a text field and it has the advantages of restricting input to a range of acceptable values.
Sliders are horizontal by default. The orientation can be explicitly set by using tow class variables of the SwingConstants class: HORIZONTAL or VERTICAL Constructor
1. JSlider(int, int) : Slider with the specified minimum value and maximum value. 2. JSlider(int,int,int) : Slider with the specified minimum value and maximum value
and a string value. 3. JSlider(int,int,int,int) : Slider with the specified orientation, minimum value
,maximum value and a string value. Methods:
1. setMajorTIckSpacing(int) : Separate major tick marks by the specified distance. The distance is not in pixels, but in value between the minimum and maximum values represented by the slider.
2. setMinorTIckSpacing(int) : Separate minor tick marks by the specified distance. Minor ticks are half as tall as major ticks.
3. setPaintLabels(boolean): Determine whether the numeric label of the slider should be displayed (true) or not (false).
2.1.15 JColorChooser JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.
Creating and Displaying the Color Chooser Method or Constructor Purpose 1. JColorChooser() 2. JColorChooser(Color) 3. JColorChooser(ColorSelectionModel) : Create a color chooser. The default 4. constructor creates a color chooser with an initial color of Color.white. Use the
second constructor to specify a different initial color. The ColorSelectionModel argument, when
present, provides the color chooser with a color selection model. Color showDialog(Component, String, Color) : Create and show a color chooser in a
www.vandemataramcollege.com Page 37
modal dialog. The Component argument is the parent of the dialog, the String argument specifies the dialog title, and the Color argument specifies the chooser's initial color. JDialog createDialog(Component,String,boolean, JColorChooser,ActionListener, ActionListener) : Create a dialog for the specified color chooser. As with showDialog, the Component argument is the parent of the dialog and the String argument specifies the dialog title. The other arguments are as follows: the boolean specifies whether the dialog is modal, the JColorChooser is the color chooser to display in the dialog, the first ActionListener is for the OK button, and the second is for the Cancel button. Setting or Getting the Current Color Method Purpose
1. void setColor(Color) 2. void setColor(int, int, int) 3. void setColor(int) 4. Color getColor() : Set or get the currently selected color. The three integer
version of the setColor method interprets the three integers together as an RGB color.
A swing program to demonstrate the concept of JColorChooser
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ColorPicker extends JFrame { public ColorPicker() { super("JcolorChooser Test Frame"); setSize(200,100); final JButton go=new JButton("Show JColorChooser"); go.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Color c; //Object of Color class c=JColorChooser.showDialog(((Component)e.getSource()).getParent(),"Demo",Color.blue); go.setBackground(c); } }); getContentPane().add(go); } public static void main(String args[]) { ColorPicker cp=new ColorPicker(); cp.setVisible(true); }
www.vandemataramcollege.com Page 38
} Output:-
2.1.14 JFileChooser File choosers provide a GUI for navigating the file system, and then either choosing a file or directory from a list, or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser. Another way to present a file chooser is to add an instance of JFileChooser to a container. The JFileChooser API makes it easy to bring up open and save dialogs. The type of look and feel determines what these standard dialogs look like and how they differ. In the Java look and feel, the save dialog looks the same as the open dialog, except for the title on the dialog's window and the text on the button that approves the operation. Creating and Showing the File Chooser Constructor
1. JFileChooser() 2. JFileChooser(File) 3. JFileChooser(String) : Creates a file chooser instance. The File and String
arguments, when present, provide the initial directory. Method
1. int showOpenDialog(Component) 2. int showSaveDialog(Component) 3. int showDialog(Component, String) : Shows a modal dialog containing the file
chooser. These methods return APPROVE_OPTION if the user approved the operation and CANCEL_OPTION if the user cancelled it. Another possible return value is ERROR_OPTION, which means an unanticipated error occurred.
Selecting Files and Directories Method Purpose
1. void setSelectedFile(File) 2. File getSelectedFile() :Sets or obtains the currently selected file or (if directory 3. selection has been enabled) directory. 4. void setSelectedFiles(File[])
www.vandemataramcollege.com Page 39
5. File[] getSelectedFiles() Sets or obtains the currently selected files if the file chooser is set to allow multiple selection.
6. void setFileSelectionMode(int) 7. void getFileSelectionMode() 8. boolean isDirectory SelectionEnabled() 9. boolean isFile Selection Enabled() : Sets or obtains the file selection mode.
Acceptable values are FILES_ONLY (the default), DIRECTORIES_ONLY, and FILES_AND_DIRECTORIES. Interprets whether directories or files are selectableaccording to the current selection mode.
10. Void setMultiSelectionEnabled(boolean) 11. boolean isMultiSelectionEnabled() : Sets or interprets whether multiple files can
be selected at once. By default, a user can choose only one file. JOptionPane 2.3 PRINTING WITH 2D API
www.vandemataramcollege.com Page 40
The Java 2D printing API is the java.awt.print package that is part of the Java 2 SE,version 1.2 and later. The Java 2D printing API provides for creating a PrinterJob, displaying a printer dialog to the user, and printing paginated graphics using the same java.awt.Graphics and java.awt.Graphics2D classes that are used to draw to the screen. Many of the features that are new in the Java Print Service, such as printer discovery and specification of printing attributes, are also very important to users of the Java 2D printing API. To make these features available to users of Java 2D printing, the java.awt.print package has been updated for version 1.4 of the JavaTM 2 SE to allow access to the JavaTM Print Service from the Java 2D printing API. Developers of Java 2D printing applications have four ways of using the Java Print Service with the Java 2D API: • Print 2D graphics using PrinterJob. • Stream 2D graphics using PrinterJob • Print 2D graphics using using DocPrintJob and a serviceformatted DocFlavor • Stream 2D graphics using DocPrintJob and a service-formatted DocFlavor 2.4 JAVA PRINT SERVICES API The Java Print Service (JPS) is a new Java Print API that is designed to support printing on all Java platforms, including platforms requiring a small footprint, but also supports the current Java 2 Print API. This unified Java Print API includes extensible print attributes based on the standard attributes specified in the Internet Printing Protocol (IPP) 1.1 from the IETF Specification, RFC 2911. With the attributes, client and server applications can discover and select printers that have the capabilities specified by the attributes. In addition to the included StreamPrintService, which allows applications to transcode print data to different formats, a third party can dynamically install their own print services through the Service Provider Interface. The Java Print Service API unifies and extends printing on the Java platform by addressing many of the common printing needs of both client and server applications that are not met by the current Java printing APIs. In addition to supporting the current Java 2D printing features, the Java Print Service offers many improvements, including: • Both client and server applications can discover and select printers based on their capabilities and specify the properties of a print job. Thus, the JPS provides the missing component in a printing subsystem: programmatic printer discovery. • Implementations of standard IPP attributes are included in the JPS API as first-class objects. • Applications can extend the attributes included with the JPS API. • Third parties can plug in their own print services with the Service Provider Interface.
www.vandemataramcollege.com Page 41
JDBC
JAVA DATABASE CONNECTIVITY
JDBC driver
The JDBC API defines the Java interfaces and classes that programmers use to
connect to databases and send queries. A JDBC driver implements these interfaces
and classes for a particular DBMS vendor. The JDBC driver converts JDBC calls into a
network or database protocol or into a database library API call that makes
communication with the database. This translation layer provides JDBC applications
with database autonomy . In the case of any back-end database change, only we need
to just replace the JDBC driver &some code modifications are required. “The Java
program that uses the JDBC API loads the specified driver for a particular DBMS before
it actually connects to a database. After that the JDBC DriverManager class then sends
all JDBC API calls to the loaded driver”.
There are four types of JDBC drivers as follows:
1) Type 1- JDBC-ODBC Bridge plus ODBC driver:
This driver converts JDBC API calls into Microsoft Open Database Connectivity (ODBC)
calls that are then passed to the ODBC driver. The ODBC binary code must be loaded
on every client computer that uses this type of driver.
Advantage: The JDBC-ODBC Bridge allows access to almost any database, since the
database's ODBC drivers are already available.
Disadvantages:
portable.
es.
www.vandemataramcollege.com Page 42
2) Type 2 - Native-API/ Partly Java driver:
This driver converts JDBC API calls into DBMSprecise client API calls. Similar to the
bridge driver, this type of driver requires that some binary code be loaded on each client
computer.
Advantage: This type of divers are normally offer better performance than the
JDBCODBC Bridge as the layers of communication are less than that it and also it uses
Resident / NativeAPI which is Database specific.
Disadvantage:
cannot be used for the Internet Applications.
-ODBC Bridge drivers, it is not coded in Java which cause to portability
issue.
specific to a database.
3) Type 3 - JDBC-Net/Pure Java Driver:
This driver sends JDBC API calls to a middle tier Net Server that translates the calls into
the DBMS precise Network protocol. The translated calls are then sent to a particular
DBMS.
Advantage:
. It is suitable for the web
Applications.
based, so there is no need for any vendor database library to be
present on client machines.
performance, and scalability.
fast to load.
www.vandemataramcollege.com Page 43
and auditing.
Disadvantage : This driver It requires another server application to install and maintain.
Traversing the recordset may take longer, since the data comes through the back-end
server.
4)Type 4 - Native-protocol/Pure Java driver:
This driver converts JDBC API calls directly into the DBMSprecise network protocol
without a middle tier. This allows the client applications to connect directly to the
database server.
Advantage:
eliminate deployment administration issues. It is most suitable for the web.
er number of translation layers are very less i.e. type 4 JDBC drivers
don't need to translate database requests to ODBC or a native connectivity
interface or to pass the request on to another server.
nt or server.
Disadvantage: With this type of drivers, the user needs a different driver for each
database.
JDBC architecture.
JDBC is a Java API for executing SQL statements and supports basic SQL functionality.
The JDBC (Java Database Connectivity) is an API that defines interfaces and classes
for writing database applications in Java by making database connections.
It is a program designed to access many popular database products on a number of
operating system platforms. Using JDBC we can send SQL, PL/SQL statements to
almost any relational database. It provides RDBMS access by allowing us to embed
SQL inside Java code.
www.vandemataramcollege.com Page 44
The main function of the JDBC API is to provide a means for the developer to issue
SQL statements and process the results in a consistent, database independently. JDBC
provides wealthy object-oriented access to databases by defining classes and
interfaces that represent objects such as:
SQL statements, Result Set:
Database driver
(explain in short)
The JDBC API uses a Driver Manager and database precise drivers to provide clear
connectivity to heterogeneous databases. The JDBC driver manager ensures that the
correct driver is used to access each data source. The Driver Manager is capable of
supporting multiple concurrent drivers connected to multiple heterogeneous databases.
Layers of the JDBC Architecture
Driver Manager Introduction
Java’s Driver Manager controls interaction between the UI and the database driver
being used. It can support multiple drivers connecting to different DBMS system. The
www.vandemataramcollege.com Page 45
driver manager loads the requested driver and provide support for managing database
connections. The driver manager can perform the following tasks.
Locate a driver for a particular database.
Process a JDBC initialization calls
Provides entry points to JDBC functions for each specific driver.
Perform parameter and sequence validation for JDBC calls.
The DriverManager class: The DriverManager class works as the interface between
the application(UI) and the ODBC driver created to communicate with the database.
The DriverManager also provides a set of in-built methods for managing database
drivers. Following are the methods of DriverManager class.
Connection getConnection (String url, user,password): The getConnection
method attempts to establish a connection to the specified database by invoking
the driver and accepting the name of the system DSN.
Connection getConnection (String url) : Attempts to establish a connection
to the given database URL.
Driver getDriver(String url) : Attempts to locate a driver that understands the
given URL.
If it is successful it returns a Connection object which represents a physical connection
to the database.
Once a physical connection with the database has been established initialization of the
SQL queries that will be fired against the database is done.
Connection Interface: A Connection object represents a Connection with a
database. Within this session SQL statements can be executed, returning resultsets.
Some of the widely used methods of the connection object are
void close(): The close method provides for immediate release of the
Connection’s database resources. Errors that occur when this method is used
throw an SQLException.
www.vandemataramcollege.com Page 46
boolean isClosed() : Tests to see if a Connection is closed.
Statement CreateStatement() : This method returns a new statements object
that can be used to execute SQL statements. Errors that occur when this method
is used throw an SQLException.
Statement Interface : The Statements object execute SQL statements that are static
and obtain results following their execution. Results are in the form of a ResultSet
Object. Some of the important methods are:
ResultSet executeQuery (String SQL_Statement) : This method executes an
SQL statements that returns a single ResultSet object. A SQLException is
thrown in case of error.
int executeUpdate (String SQL_Statement) : This method executes an SQL
UPDATE, DELETE or INSERT statements. A row count is returned by these
statements. The return value is zero if the SQL statement does not return any
rows. Errors that occur when this method is used throw SQLException.
void close(): Release the Statement objects database and JDBC resources
immediately instead of waiting for this to happen when it is automatically closed.
void cancel(): Cancels this Statement object if both the DBMS and driver
support aborting SQL statement.
PreparedStatement Interface: The interface PreparedStatement extends the
Statement interface. If the application requires multiple executions of a particular
SQL statement, it is pre-compiled and stored in a PreparedStatement object. This
object can then used many times to execute the statement efficiently. Some of the
most widely used methods of this interface are as follows.
ResultSet executeQuery(): This method is used to execute SQL statements.
SQLException exception is thrown in case of errors.
Int executeUpdate() : This method executes SQL UPDATE, DELETE or
INSERT statements. SQL statements that do not return anything such as
www.vandemataramcollege.com Page 47
SQL DDL statements can also be executed. Errors that occur when this
method is used throw an SQLException.
Program for PreparedStatement
import java.sql.*;
public class prepare
{
public static void main(String a[]) throws Exception
{
PreparedStatement ps=null;
Connection con=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:data");
ps=con.prepareStatement("insert into stud values(?,?,?)");
ps.setInt(1, 22);
ps.setString(2, "bbb");
ps.setString(3, "mumbai");
System.out.println("record is added");
ps.executeUpdate();
ps.close();
con.close();
}
catch(SQLException e)
{
System.out.println("error"+e);
}
}
}
www.vandemataramcollege.com Page 48
ResultSetInterface: The data that is generated by the execution of a SQL statement is
stored in and can be accessed, from a ResultSet object. The ResultSet object watches
a single row of data at a time. This row of data is called its current row. When an SQL
statement is re-executed the current ResultSet is automatically closed and a new
ResultSet is created. Some of the methods of the ResultSet are:
void close(): The method is used when the application wants to release a
ResultSet database resources and JDBC resources immediately.
void getString(): This method gets the value of a column in the current row as a
java String.
void afterLast(): Moves the cursor to the end of this ResultSet object just after
the last row.
void beforeFirst(): Moves the cursor to the front of this ResultSet object just
before the last row.
void deleteRow(): Deletes the current row from this ResulSet object and from
the underlying database.
next(): A ResultSet is initially positioned before its first rpw the first call to the
next makes the first row the current row, the second call makes the second row
the current row etc.
ResultSetMetaData Interface: The ResultSetMetaData object returned by the
getMetaData() constructor provides access to information which indicates the number
type and properties of ResultSet columns. Some of the methods of the
ResultSetMetaData are as:
getColumnCount(): This method returns the number of columns in the
ResultSet.
String getColumnName(int col): This method returns the name of the column.
getTableName(): This method returns the name of table.
Example - Write a JDBC program to create a table and insert records into it.
import java.sql.*;
public class FirstJDBC
www.vandemataramcollege.com Page 49
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e){
System.out.println("Error"+e.getMessage());}
try
{
Connection con =
DriverManager.getConnection("jdbc:odbc:myDSN");
Statement st = con.createStatement();
String str = "create table Login (UserName text,Password text)";
st.executeUpdate(str);
System.out.println("Table Created");
st.executeUpdate("insert into Login values ('Ram','abc')");
st.executeUpdate("insert into Login values ('Harsh','hhh')");
st.executeUpdate("insert into Login values ('Ram','gfg')");
st.executeUpdate("insert into Login values ('Raju','ggg')");
st.executeUpdate("insert into Login values ('Ramu','mmm')");
con.commit();
System.out.println("Values Inserted");
}
catch(Exception
e){System.out.println("Error"+e.getMessage());}
}
}
Note: To run the program we need to create a DSN. Here are the steps to create.
www.vandemataramcollege.com Page 50
2) Click on Data Sources (ODBC) which opens a dialog box. Click Add button.
3) Select the driver for your database and click on Finish button.
4) Give name myDSN and select your database which was already created.
Example - Write a JDBC program to fetch values and display them on screen.
import java.sql.*;
public class SelDemo
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc: myDSN ");
Statement st = con.createStatement();
ResultSet sel = st.executeQuery("select * from Login");
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());
}
}
}
www.vandemataramcollege.com Page 51
Example - 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: myDSN");
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());
}
}
}
www.vandemataramcollege.com Page 52
Program for type 1 driver
import java.sql.*;
class type1
{
public static void main(String a[])throws Exception
{ try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:data";
Connection con=DriverManager.getConnection(url,"","");
System.out.println("successfully connected");
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getString("name"));
System.out.println(rs.getString("add"));
System.out.println(rs.getString("city"));
System.out.println(rs.getInt("contact"));
System.out.println("");
}
con.close();
rs.close();
s.close();
}
catch(SQLException e)
{
www.vandemataramcollege.com Page 53
System.out.println("error"+e.getMessage());
}
}
}
Program for update record
import java.sql.*;
public class update
{
public static void main(String a[])throws Exception
{ try
{
String q="select * from emp";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:data";
Connection con=DriverManager.getConnection(url,"","");
Statement s=con.createStatement();
//int p= s.executeUpdate("update emp" + "set name='yy'" + "where //city='MUMBAI'");
int p=s.executeUpdate("update emp set name='rr' where city='MUMBAI'");
System.out.println(p + "Row Updated");
ResultSet rs=s.executeQuery(q);
System.out.println("Name\t Add\t City\t Contact\t");
while(rs.next())
{
String name=rs.getString("name");
String add=rs.getString("add");
String city=rs.getString("city");
int contact=rs.getInt("contact");
www.vandemataramcollege.com Page 54
System.out.println(name + "\t" + add + "\t" +city +"\t" +contact+"\t");
}
con.close();
}
catch(SQLException e)
{ System.out.println("error"+e.getMessage());
}
}}
Program for delete all records & for drop table
import java.sql.*;
public class droptable
{
public static void main(String a[])throws Exception
{ try
{
String q="select * from emp";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:data";
Connection con=DriverManager.getConnection(url,"","");
Statement s=con.createStatement();
// s.executeUpdate("delete * from demo");
// it delete only records from table
s.executeUpdate("drop table demo");
//it delete completetable with its structure
System.out.println("table deleted");
con.close();
www.vandemataramcollege.com Page 55
}
catch(SQLException e)
{
System.out.println("error"+e.getMessage());
}
}
}
Program to insert a new record in to table
import java.sql.*;
public class insertion
{
public static void main(String a[])throws Exception
{ try
{
String q="select * from emp";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:data";
Connection con=DriverManager.getConnection(url,"","");
Statement s=con.createStatement();
int p=s.executeUpdate("insert into emp values (5 ,'Abc','dombivli’, 'Mumbai',
3434343)");
System.out.println(p + "Row Inserted");
ResultSet rs=s.executeQuery(q);
System.out.println("Name\t Add\t City\t Contact\t");
while(rs.next())
{
String name=rs.getString("name");
www.vandemataramcollege.com Page 56
String add=rs.getString("add");
String city=rs.getString("city");
int contact=rs.getInt("contact");
System.out.println(name + "\t" + add + "\t" +city +"\t" +contact+"\t");
}
con.close();
}
catch(SQLException e)
{
System.out.println("error"+e.getMessage());
}
}
}
THE JAVA.SQL PACKAGE:-
The java.sql package contains various interfaces and classes used by the JDBC APL.
This collection of interfaces and classes enable the primary functions of opening and
managing connections to a particular DBMSystem. Executing SQL statements.
Processing the results.
DriverManager Class
The DriverManager class is available in the java.sql package. It controls the interface
between the application and a set of JDBC drivers. The DriverManager also provides a
set of methods for managing the drivers. The DriverManager is used t locate a suitable
driver from amongst those loaded on the computer. Some f the methods used are:
getConnection(URL,user,Password)
the getConnection method attempts to establish a connection to the specified
database URL(i.e a path specified to where the database is on the harddisk). If it
is successful, it returns a Connection object, which represents a connection to
the database.
www.vandemataramcollege.com Page 57
Connection Interface
A connection object represents a connection with a database. Within this session
SQL statements can be executed, returning resultsets. Some of the widely used
methods of the connection object are:
void close()
The close method provides for immediate release of the connection’s database
resource and JDBC resources. Errors that occur when this method is used throw
an SQLException.
Statement CreateStatement()
This method returns a new statement object that can be used to execute SQL
statements. Error that occurs when this method is used throw an
SQLExeception.
Statement Interface
The Statement object exeute SQL statements that are static and obtain results following
their execution. Results are in the form of a ResultSet object.
Some of the important methos are:
ResultSet executeQuery(String SQL_Statement)
This metho executes an SQL statement that returns a single ResultSet object. A
SQLException is thrown in case f error.
Int executeUpdate(String SQL_Statement) : This method executes SQL
UPDATE, DELETE, or INSERT statements. A row count is returned by these
statements. The return value is zero if the SQL statement oes not return any
rows. Errors that occur when this method is used throw an SQLException.
PreparedStatement Interface
The interface PreaperedStatement extends the Statement interface. If the application
requires multiple execution of a particular SQL statement, it is pre-compiled and stored
www.vandemataramcollege.com Page 58
in a PreaparedStatement object. This object can then be used many times to execute
the statement efficiently. Some of the most widely used methods of this interface are as
follows.
executeQuery() : This method is used to execute SQL statements.
SQLException exception is thrown in case of errors.
executeUpdate() : This method executes SQL UPDATE, DELETE, or INSERT
statements. SQL statements that do not return anything such as SQL DDL
statements can also be executed. Errors that occur when this method is used
thrown an SQLException.
Resultset Interface
The data that is generated by the execution of a SQl statement is stored in, and can be
accessed ,from a resultset object. The Ruleset Object ‘watches’ a single row Of data at
a time. This row of data is called its current row. When an SQL statement is re-executed
The current result set is automatically closed and a new RecordSet object is created.
Some of the methods of the RecordSet object are:
void close() : the method is used when the application wants to release a
RuleSet database resource and JDBC resources immediately.
Void getString() : This method gets te value of a column in the current row as a
Java String.
Next() : A Ruleset is initially positioned before its first row,the first call to the next
makes the first row the current row ,the second call makes the second row the
current row etc.
ResultSetMetaData Interface
www.vandemataramcollege.com Page 59
The ResultsetMetaData Object returned by the getMetaData() constructor provides
acess to information which indicates the number,type and properties of Ruleset
columns.Some of its important methods are:
getColumnCount() : This method returns the number of columns int the
RuleSet.
String getColumnName(int) : This method returns the name of the column.
getTableName() : This method returns the name of a table.
THE JDBC EXCEPTION CLASSES
SQL Warning Data Truncation SQL Exception
The JDBC Exception classes are as follows:
SQL Warning class : The java.sql.SQLWarning class extends the
java.sql.SQLException clss. The SQLWarning class provides information about a
database access warning. When a method of an object causes a warning to be
reported, the warning is chained to that object. Some of the methods used are:
SQL Warning getNextWarning()
This method returns the SQLWarning chained t the current SQLWarning object.
Void setNextWarning(SQLWarning nextWarning)
This method adds a SQLWarning object to the end of chain.
Data Truncation class
The DataTrunction class extends the java.sql.SQLWarning class. When JDBC truncates
a value unexpectedly, it reports a DataqTrunction warning for a read process, or white
process.
www.vandemataramcollege.com Page 60
Int getIndex() : This method returns the index of the column or the parameter
that was truncated. The return value is-1, if the column or parameter index is
unknown. In this case, the “parameter” and “read” fields of the DataTruncation
object should be ignored.
Boolean getparameter() : If the truncated value was a parameter the value
returned is True if the truncated value was a column, the value returned is False.
Boolean getRead() : If the value was trunvated while being read from a
database, the value returned is True. If the value was truncated when writing to a
database the value False is returned.
SQLExeception class : The java.sql.SQLExecption class extends the
java.lang.Exception class. The SQLException class provides information about a
database access error. Some of the important methods of this class are:
Int getErrorCode() : This method returns the vender specific exception code.
String getSQLState() : This method returns the SQLState.
SQLException getNextException() : This method is used to obtain the next
exception, chained to the current exception.
4.2 PREPARED STATEMENTS:
A PreparedStatement object is more convenient for sending SQL statements to the
database. This special type of statement is derived from the more general class,
Statement. If you want to execute a Statement object many times, use a
PreparedStatement object instead which reduces execution time.
The main feature of a Prepared Statement object is that it is given an SQL statement
when it is created. The advantage to this is that in most cases, this SQL statement is
sent to the DBMS right away, where it is compiled. As a result, the Prepared Statement
object contains not just an SQL statement, but an SQL statement that has been
precompiled. This means that when the PreparedStatement is executed, the DBMS can
just run the PreparedStatement SQL statement without having to compile it first.
www.vandemataramcollege.com Page 61
Although PreparedStatement objects can be used for SQL statements with no
parameters, we use them most often for SQL statements that take parameters. The
advantage of using SQL statements that take parameters is that you can use the same
statement and supply it with different values each time you execute it.
Creating a PreparedStatement Object
A PreparedStatement objects can be created with a Connection method.
E.g. PreparedStatement updateEmp = con.prepareStatement("UPDATE EMPLOYEES
SET SALARY = ? WHERE EMP_ID = ?");
Supplying Values for PreparedStatement Parameters
You need to supply values to be used in place of the question mark placeholders (if
there are any) before you can execute a PreparedStatement object. You do this by
calling one of the setXXX methods defined in the PreparedStatement class.
If the value you want to substitute for a question mark is a Java int, you call the method
setInt. If the value you want to substitute for a question mark is a Java String, you call
the method setString, and so on. In general, there is a setXXX method for each primitive
type declared in the Java programming language.
updateEmp.setInt(1, 7500);
updateEmp.setInt(2,1030);
updateEmp.executeUpdate():
The method executeUpdate was used to execute both the Statement stmt and the
Prepared Statement update Emp. Notice, however, that no argument is supplied to
execute Update when it is used to execute update Emp. This is true because update
Emp already contains the SQL statement to be executed.
4.4 TRANSACTIONS
Committing a Transaction
www.vandemataramcollege.com Page 62
Once auto-commit mode is disabled, no SQL statements are committed until you call
the method commit explicitly. All statements executed after the previous call to the
method commit are included in the current transaction and committed together as a unit.
The following code, in which con is an active connection, illustrates a transaction:
con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET
TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
Types of Result Sets
Results sets may have different levels of functionality. For example, they may be
scrollable or non-scrollable. A scrollable result set has a cursor that moves both forward
and backward and can be moved to a particular row. Also, result sets may be sensitive
or insensitive to changes made while they are open; that is, they may or may not reflect
changes to column values that are modified in the database.
The following constants, defined in the ResultSet interface, are used to specify these
three types of result sets:
1. TYPE_FORWARD_ONLY
www.vandemataramcollege.com Page 63
results incrementally.
2. TYPE_SCROLL_INSENSITIVE
he result set is scrollable: Its cursor can move forward or backward and can be
moved to a particular row or to a row whose position is relative to its current position.
made while it is open. The membership, order, and column values of rows are typically
fixed when the result set is created.
3. TYPE_SCROLL_SENSITIVE
moved to a particular row or to a row whose position is relative to its current position.
values are modified, the new values are visible, thus providing a dynamic view of the
underlying data. The membership and ordering of rows in the result set may be fixed or
not, depending on the implementation.
Concurrency Types
A result set may have different update capabilities. As with scrollability, making a
ResultSet object updatable increases overhead and should be done only when
necessary.
1. CONCUR_READ_ONLY
users). When a ResultSet object with read-only concurrency needs to set a lock, it uses
a read-only lock. This allow users to read data but not to change it. Because there is no
limit to the number of readonly locks that may be held on data at one time, there is no
limit to the number of concurrent users unless the DBMS or driver imposes one.
2. CONCUR_UPDATABLE
-only locks
so that only one user at a time has access to a data item. This eliminates the possibility
www.vandemataramcollege.com Page 64
that two or more users might change the same data, thus ensuring database
consistency. However, the price for this consistency is a reduced level of concurrency.
Scrollable and Updateable ResultSets
As we know that ResultSet moving only in forward direction. If some properties are set
while creating the ResultSet then we can randomly fetch the data and even update it
witout any update queries.
The next example demonstrates the advance features of the ResultSet.
import java.sql.*;
public class rscrollupdate
{
public static void main(String[] args) throws SQLException,
ClassNotFoundException
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:data");
Statement stmt
=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UP
DATABLE);
ResultSet rs=stmt.executeQuery("select * from stud");
while(rs.next())
{
System.out.println("Id is =" +rs.getInt("rollno"));
System.out.println(" Name is = "+rs.getString("name"));
System.out.println(" city is = "+rs.getString("city"));
System.out.println(" ");
}
rs.absolute(1);
www.vandemataramcollege.com Page 65
rs.updateString(2,"priya");
rs.updateString(3,"dom");
rs.updateRow();
rs.beforeFirst();
System.out.println("After Updation");
while(rs.next())
{
System.out.println("Id is= " +rs.getInt("rollno"));
System.out.println(" Name is= "+rs.getString("name"));
System.out.println(" city is= "+rs.getString("city"));
System.out.println(" ");
}
stmt.close();
con.close();
}
}
4.5 STORED PROCEDURES
A stored procedure is a group of SQL statements that form alogical unit and perform a
particular task, and they are used to encapsulate a set of operations or queries to
execute on a database server. For example, operations on an employee database (hire,
fire, promote, lookup) could be coded as stored procedures executed by application
code. Stored procedures can be compiled and executed with different parameters and
results, and they may have any combination of input, output, and input/output
parameters. This simple stored procedure has no parameters. Even though most
stored procedures do something more complex than this example, it serves to illustrate
some basic points about them. In some DBMSs, the following SQL statementcreates a
stored procedure:
create procedure SHOW_SUPPLIERS
as
select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME
www.vandemataramcollege.com Page 66
from SUPPLIERS, COFFEES
where SUPPLIERS.SUP_ID = COFFEES.SUP_ID
order by SUP_NAME
String createProcedure = "create procedure SHOW_SUPPLIERS "
+ "as " + "select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME
" + "from SUPPLIERS, COFFEES " + "where SUPPLIERS.SUP_ID
= COFFEES.SUP_ID " + "order by SUP_NAME";
The following code fragment uses
the Connection object con to create a Statement object, which is
used to send the SQL statement creating the stored procedure to
the database:
Statement stmt = con.createStatement();
stmt.executeUpdate(createProcedure);
The procedure SHOW_SUPPLIERS is compiled and stored in the database as a
database object that can be called, similar to the way you would call a method.
Calling a Stored Procedure from JDBC
An application written in the Java programming language. The first step is to create a
Callable Statement object. As with Statement and Prepared Statement objects, this is
done with an open Connection object. A callable Statement object contains a call to a
stored procedure; it does not contain the stored procedure itself. The first line of code
below creates a call to the stored procedure SHOW_SUPPLIERS using the connection
con. The part that is enclosed in curly braces is the escape syntax for stored
procedures. When the driver encounters "{call SHOW_SUPPLIERS}", it will translate
this escape syntax into the
native SQL used by the database to call the stored procedure
named SHOW_SUPPLIERS.
www.vandemataramcollege.com Page 67
CallableStatement cs = con.prepareCall
("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
The ResultSet rs will be similar to the following:
SUP_NAME COF_NAME
---------------- -----------------------
Reliance Colombian
Reliance Colombian_Decaf
Tata French_Roast
Tata French_Roast_Decaf
Sahara Espresso
Example - 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.
www.vandemataramcollege.com Page 68
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());
}
} }
www.vandemataramcollege.com Page 69
Java Server Pages (JSP)
1. Introduction
JavaServer Page (JSP) is Java's answer to the popular Microsoft's Active Server Pages (ASP).
JSP, like ASP, provides a simplified and fast mean to generate dynamicweb contents. It allows
you to mix static HTML with dynamically generated HTML - in the way that the business
logic and the presentation are well separated.
The advantages of JSP are:
1.Separation of static and dynamic contents: JSP enables the separation
of static contents from dynamic contents. The dynamic contents are generated via
programming logic and inserted into the static template. This greatly simplifies the
creation and maintenance of web contents.
2.Reuse of components and tag libraries: The dynamic contents can be provided by
reusable components such as JavaBean, Enterprise JavaBean (EJB) and tag libraries -
you do not have to re-inventing the wheels.
3.Java's power and portability
JSPs are Internally Compiled into Java Servlets
That is to say, anything that can be done using JSPs can also be accomplished using Java
servlets. However, it is important to note that servlets and JSPs are complementary technologies,
NOT replacement of each other. Servlet can be viewed as "HTML inside Java", which is better
for implementing business logic - as it is Java dominant. JSP, on the other hand, is "Java inside
HTML", which is superior for creating presentation - as it is HTML dominant. In a
typical Model-View-Control (MVC) application, servlets are often used for the Controller (C),
which involves complex programming logic. JSPs are often used for the View (V), which mainly
deals with presentation. The Model (M) is usually implemented using JavaBean or EJB.
Apache Tomcat Server
JSPs, like servlets, are server-side programs run inside a HTTP server. To support JSP/servlet, a
Java-capable HTTP server is required. Tomcat Server (@ http://tomcat.apache.org) is the
official reference implementation (RI) for Java servlet and JSP, provided free by Apache
(@ http://www.apache.org) - an open-source software foundation.
www.vandemataramcollege.com Page 70
2. First JSP Example - "Java inside HTML"
Let's begin with a simple JSP example. We shall use the webapp called "hello" that we have
created in our earlier exercise. Use a programming text editor to enter the following HTML/JSP
codes and save as "first.jsp" (the file type of ".jsp" is mandatory) in your webapp (web context)
home directory (i.e., "webapps\hello".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<html>
<head><title>First JSP</title></head>
<body>
<%
double num = Math.random();
if (num > 0.95) {
%>
<h2>You'll have a luck day!</h2><p>(<%= num %>)</p>
<%
} else {
%>
<h2>Well, life goes on ... </h2><p>(<%= num %>)</p>
<%
}
%>
<a href="<%= request.getRequestURI() %>"><h3>Try Again</h3></a>
</body>
</html>
To execute the JSP script: Simply start your Tomcat server and use a browser to issue an URL to
browse the JSP page (i.e., http://localhost:8080/hello/first.jsp).
From your browser, choose the "View Source" option to check the response message. It should
be either of the followings depending on the random number generated.
<html>
<h2>You'll have a luck day!</h2>
www.vandemataramcollege.com Page 71
<p>(0.987)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
<html>
<h2> Well, life goes on ... </h2>
<p>(0.501)</p>
<a href="first.jsp"><h3>Try Again</h3></a>
</html>
It is important to note that the client is not able to "view" the original JSP script (otherwise, you
may have security exposure), but merely the result generated by the script.
Explanations
1.A JSP script is a regular HTML page containing Java programs. Recall that JSP is "Java
inside HTML" (whereas servlet is "HTML inside Java"). The Java statements are
enclosed by <% ... %> (called JSP scriptlet) or <%= ... %> (called JSP expression).
2.JSP Scriptlet <% ... %> is used to include Java statements.
3.JSP Expression <%= ... %> is used to evaluate a single Java expression and display its
result.
4.The method request.getRequestURI() is used to retrieve the URL of the current page.
This is used in the anchor tag <a> for refreshing the page to obtain another random
number.
Behind the Scene
When a JSP is first accessed, Tomcat converts the JSP into a servlet; compile the servlet,
and execute the servlet. Check out the generated servlet for "first.jsp", and study the JSP-to-
servlet conversion. Look under Tomcat's "work\Catalina\localhost\hello" for "first_jsp.java".
The relevant part of the generated servlet is extracted as follows (with some simplifications):
1
2
out.write("<html>\r\n ");
double num = Math.random();
www.vandemataramcollege.com Page 72
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
if (num > 0.95) {
out.write("<h2>You will have a luck day!");
out.write("</h2><p>(");
out.print( num );
out.write(")</p>\r\n");
} else {
out.write("\r\n ");
out.write("<h2>Well, life goes on ... ");
out.write("</h2><p>(");
out.print( num );
out.write(")</p>\r\n ");
}
out.write("<a href=\"");
out.print( request.getRequestURI() );
out.write("\">");
out.write("<h3>Try Again</h3></a>\r\n");
out.write("</html>\r\n");
Explanation
1.The HTML statements are written out as part of the response via out.write(), as "it is".
2.The JSP scriptlets <% ... %> are kept, as "it is", in the converted servlet as the program
logic.
3.The JSP expressions <%= ... %> are placed inside a out.print(). Hence, the expression
will be evaluated, and the result of the evaluation written out as part of the response
message.
Compare the JSP script and the internally generated servlet, you shall understand that servlet is
"HTML inside Java", whereas JSP is "Java inside HTML".
Subsequent accesses to the same JSP will be much faster, because they will be re-directed to the
converted and compiled servlet directly (no JSP-to-servlet conversion and servlet compilation
needed again), unless the JSP has been modified.
3. Revisit Java Servlets
www.vandemataramcollege.com Page 73
A typical Java servlet (as shown below) contains three kinds of methods: init(), destroy(), and
one or more service() methods such as doGet() and doPost(). init() runs when the servlet is
loaded.destroy() runs when the servlet is unloaded. service() runs once per HTTP request.
The service() methods takes two arguments: request and response, corresponding to the HTTP
request and response messages respectively. A PrintWriter called out is created for writing out
the response to the network.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ...Servlet extends HttpServlet {
// Runs when the servlet is loaded onto the server.
public void init() {
......
}
// Runs on a thread whenever there is HTTP GET request
// Take 2 arguments, corresponding to HTTP request and response
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Write to network
PrintWriter out = response.getWriter();
// Your servlet's logic here
out.println("<html>");
out.println( ...... );
www.vandemataramcollege.com Page 74
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
out.println("</html>");
}
// Runs as a thread whenever there is HTTP POST request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// do the same thing as HTTP GET request
doGet(request, response);
}
// Runs when the servlet is unloaded from the server.
public void destroy() {
......
}
// Other instance variables and methods
}
Java servlet produces HTML codes by calling out.print() methods. You have to hardcode all the
HTML tags (and cannot use any WYSIWYG web authoring tools). Any change to the web
page's presentation (such as background color and font size) requires re-coding and re-
compilation of servlet program. Servlet, in a nutshell, is "HTML inside Java", whereas JSP is
"Java inside HTML".
4. Second JSP example - Echoing HTML Request Parameters
Enter the following JSP script and save as "echo.jsp" in your webapp's root directory.
1
2
3
4
5
6
<html>
<head>
<title>Echoing HTML Request Parameters</title>
</head>
<body>
<h3>Choose an author:</h3>
www.vandemataramcollege.com Page 75
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<form method="get">
<input type="checkbox" name="author" value="Tan Ah Teck">Tan
<input type="checkbox" name="author" value="Mohd Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Query">
</form>
<%
String[] authors = request.getParameterValues("author");
if (authors != null) {
%>
<h3>You have selected author(s):</h3>
<ul>
<%
for (int i = 0; i < authors.length; ++i) {
%>
<li><%= authors[i] %></li>
<%
}
%>
</ul>
<a href="<%= request.getRequestURI() %>">BACK</a>
<%
}
%>
</body>
</html>
Browse the JSP page created and study the generated servlet.
Explanations
www.vandemataramcollege.com Page 76
1.This HTML page has a form with 3 checkboxes. The "name=value" pair of the
checkboxes is "author=so_and_so". No "action" attribute is specified, the default
"action" is the current page (i.e. the query will be sent to the same page).
2.The JSP scriptlet checks if the query parameter "author" exists to decide whether to
dynamically generate the enclosed codes. "author" parameter is absent when the page is
first requested. Once the client fills in the form (by checking the boxes) and submits the
form, "author" will be present in the HTTP request, and submitted to the same page for
processing (with the default <form>’s "action" attribute).
3.The request.getParameterValues() is used to retrieve all the values of the query
parameter. The values are echoed back using an unordered list.
5. JSP Scripting Elements
JSP provides the following scripting elements:
JSP Comment <%-- comments -->
JSP Expression <%= Java Expression %>
JSP Scriptlet <% Java Statement(s) %>
JSP Directive <%@ page|include ... %>
To simplify the access of the HTTP request and response messages, JSP has pre-defined the
following variables:
request: corresponds to the HTTP request message.
response: corresponds to the HTTP response message.
out: corresponds to the HTTP response message’s output stream.
others such as session, page, application, pageContext, which are outside the scope of this
tutorial.
5.1 JSP comment <%-- comments --%>
JSP comments <%-- comments --%> are ignored by the JSP engine. For example,
<%-- anything but a closing tag here will be ignored -->
www.vandemataramcollege.com Page 77
Note that HTML comment is <!-- comments -->. JSP expression within the HTML comment will
be evaluated. For example,
<!-- HTML comments here <%= Math.random() %> more comments -->
5.2 JSP Expression <%= Java Expression %>
JSP Expression can be used to insert a single Java expression directly into the response
message. This expression will be placed inside a out.print() method. Hence, the expression will
be evaluated and printed out as part of the response message. Any valid Java expression can be
used. There is no semi-colon at the end of the expression. For examples:
<p>The square root of 5 is <%= Math.sqrt(5) %></p>
<h5><%= item[10] %></h5>
<p>Current time is: <%= new java.util.Date() %></p>
The above JSP expressions will be converted to:
out.write("<p>The square root of 5 is ");
out.print( Math.sqrt(5) );
out.write("</p>");
out.write("<h5>");
out.print( item[10] );
out.write("</h5>");
out.write("<p>Current time is: ");
out.print( new java.util.Date() );
out.write("</p>");
You can use the pre-defined variables, such as request, in the expressions. For examples:
<p>You have choose author <%= request.getParameter("author") %></p>
<%= request.getRequestURI() %>
<%= request.getHeader("Host") %>
5.3 JSP Scriptlet <% Java statement(s) %>
www.vandemataramcollege.com Page 78
JSP scriptlets allow you to do more complex operations than inserting a single Java expression
(with the JSP expression). JSP scriptlets let you insert an arbitrary sequence of valid Java
statement(s) into theservice() method of the converted servlet. All the Java statements in a
scriptlet are to be terminated with a semi-colon. For example:
<%
String author = request.getParameter("author");
if (author != null && !author.equals(""))) {
%>
<p>You have choose author <%= author %></p>
<%
}
%>
In the converted servlet, the above will be inserted into the service() method as follows:
String author = request.getParameter("author");
if (author != null && !author.equals(""))) {
out.write("<p>You have choose author ");
out.print( author );
out.write("</p>");
}
Notice that the Java codes inside a scriptlet are inserted exactly as they are written, and used as
the programming logic. The HTML codes are passed to an out.write() method and written out as
part of the response message.
5.4 JSP Directive <%@ page|include ... %>
JSP directives provide instructions to the JSP engine. The syntax of the JSP directive is:
<%@ directive_name
attribute1="value1"
attribute2="value2"
......
www.vandemataramcollege.com Page 79
attributeN="valueN" %>
JSP page Directive
The "page" directive lets you import classes and customize the page properties. For examples,
<%-- import package java.sql.* -->
<%@ page import="java.sql.*" %>
<%-- Set the output MIME type -->
<%@ page contentType="image/gif" %>
<%-- Set an information message for getServletInfo() method -->
<%@ page info="Hello-world example" %>
JSP include Directive
The "include" directive lets you include another file(s) at the time when the JSP page is compiled
into a servlet. You can include any JSP files, or static HTML files. You can use include directive
to include navigation bar, copyright statement, logo, etc. on every JSP pages. The syntax is:
<%@ include file="url" %>
For example:
<%@ include file="header.html" %>
......
<%@ include file="footer.html" %>
6. JSP Database Example
Let's revisit our e-shop, which was created using Java Servlet.
Database
Database: ebookshop
www.vandemataramcollege.com Page 80
Table: books
+-------+----------------------------+---------------+---------+-------+
| id | title | author | price | qty |
| (INT) | (VARCHAR(50)) | (VARCHAR(50)) | (FLOAT) | (INT) |
+-------+----------------------------+---------------+---------+-------+
| 1001 | Java for dummies | Tan Ah Teck | 11.11 | 11 |
| 1002 | More Java for dummies | Tan Ah Teck | 22.22 | 22 |
| 1003 | More Java for more dummies | Mohammad Ali | 33.33 | 33 |
| 1004 | A Cup of Java | Kumar | 44.44 | 44 |
| 1005 | A Teaspoon of Java | Kevin Jones | 55.55 | 55 |
+-------+----------------------------+---------------+---------+-------+
Querying - "query.jsp"
Let's create the query page called "query.jsp".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<title>Book Query</title>
</head>
<body>
<h1>Another E-Bookstore</h1>
<h3>Choose Author(s):</h3>
<form method="get">
<input type="checkbox" name="author" value="Tan Ah Teck">Tan
<input type="checkbox" name="author" value="Mohd Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Query">
</form>
<%
String[] authors = request.getParameterValues("author");
www.vandemataramcollege.com Page 81
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
if (authors != null) {
%>
<%@ page import = "java.sql.*" %>
<%
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// Connection conn =
// DriverManager.getConnection("jdbc:odbc:eshopODBC"); // Access
Statement stmt = conn.createStatement();
String sqlStr = "SELECT * FROM books WHERE author IN (";
sqlStr += "'" + authors[0] + "'"; // First author
for (int i = 1; i < authors.length; ++i) {
sqlStr += ", '" + authors[i] + "'"; // Subsequent authors need a leading commas
}
sqlStr += ") AND qty > 0 ORDER BY author ASC, title ASC";
// for debugging
System.out.println("Query statement is " + sqlStr);
ResultSet rset = stmt.executeQuery(sqlStr);
%>
<hr>
<form method="get" action="order.jsp">
<table border=1 cellpadding=5>
<tr>
<th>Order</th>
<th>Author</th>
<th>Title</th>
<th>Price</th>
<th>Qty</th>
</tr>
www.vandemataramcollege.com Page 82
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<%
while (rset.next()) {
int id = rset.getInt("id");
%>
<tr>
<td><input type="checkbox" name="id" value="<%= id %>"></td>
<td><%= rset.getString("author") %></td>
<td><%= rset.getString("title") %></td>
<td>$<%= rset.getInt("price") %></td>
<td><%= rset.getInt("qty") %></td>
</tr>
<%
}
%>
</table>
<br>
<input type="submit" value="Order">
<input type="reset" value="Clear">
</form>
<a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>
<%
rset.close();
stmt.close();
conn.close();
}
%>
</body>
</html>
Explanations
www.vandemataramcollege.com Page 83
1.This HTML page has a form with 3 checkboxes. The "name=value" pair of the
checkboxes is "author=so_and_so". No "action" attribute is specified, hence, it
defaulted to current page. The processing script is contained in the same page.
2.The method request.getParameter("author") is used to check if the query parameter
"author" exists. "author" is absent during the first reference of the page.
3.The <%@ page .. %> contains a JSP "page" directive to import the java.sql package.
4.The scriptlet performs the database query operation. The steps are:
a. Establish a database connection via a java.sql.Connection object;
b. Allocate a java.sql.Statement object under the Connection;
c. Prepare a SQL SELECT string;
d. Execute the SQL SELECT using executeQuery() method. The result of query is
returned in an object of java.sql.ResultSet;
e. Process the ResultSet row by row via ResultSet.next();
f. Free resources and close the Connection.
5.The query result is tabulated in a HTML table. Note the mixing of HTML and Java in
producing the table.
Notice that JSP carries out the presentation much better and neater than servlet. The presentation
can be changed easily with JSP. The JSP pages can be created and modified using a WYSIWYG
web authoring tool and reload to see the effect on the presentation. Whereas, in the case of
servlet, you have to explicitly code all the HTML tags inside the servlet program and re-compile
the program.
Ordering - "order.jsp"
Let's write the "order.jsp" for processing the order, by updating the appropriate records in the
database.
1
2
3
4
5
<html>
<head>
<title>Order Book</title>
</head>
www.vandemataramcollege.com Page 84
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<body>
<h1>Another E-Bookstore</h1>
<h2>Thank you for ordering...</h2>
<%
String[] ids = request.getParameterValues("id");
if (ids != null) {
%>
<%@ page import = "java.sql.*" %>
<%
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// Connection conn =
// DriverManager.getConnection("jdbc:odbc:eshopODBC"); // Access
Statement stmt = conn.createStatement();
String sqlStr;
int recordUpdated;
ResultSet rset;
%>
<table border=1 cellpadding=3 cellspacing=0>
<tr>
<th>Author</th>
<th>Title</th>
<th>Price</th>
<th>Qty In Stock</th>
</tr>
<%
for (int i = 0; i < ids.length; ++i) {
// Subtract the QtyAvailable by one
sqlStr = "UPDATE books SET qty = qty - 1 WHERE id = " + ids[i];
recordUpdated = stmt.executeUpdate(sqlStr);
www.vandemataramcollege.com Page 85
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// carry out a query to confirm
sqlStr = "SELECT * FROM books WHERE id =" + ids[i];
rset = stmt.executeQuery(sqlStr);
while (rset.next()) {
%>
<tr>
<td><%= rset.getString("author") %></td>
<td><%= rset.getString("title") %></td>
<td>$<%= rset.getInt("price") %></td>
<td><%= rset.getInt("qty") %></td>
</tr>
<% }
rset.close();
}
stmt.close();
conn.close();
}
%>
</table>
<a href="query.jsp"><h3>BACK</h3></a>
</body>
</html>
Session Handling in JSP
How is Session Handled in JSP?
Explanation
Session Handling becomes mandatory when a requested data need to be sustained for further use.
Since http protocol considers every request as a new one, session handling becomes important.
Following are some of the methods to handle session.
www.vandemataramcollege.com Page 86
In JSP whenever a request arises the server generates a unique Session ID which is stored in the
client machine.
Cookies store the information in the client browser
URL rewriting the session information is appended to the end of the URL
Hidden form fields the sessionID is embedded to GET and POST command.
Example1:
<html>
<body>
<form method = "post" action="session2.jsp">
<font>Username<input type = "text" name = "name"></font>gt;
</font><br><br>
<input type = "submit" name = "submit" value = "submit" >
</form>
</body>
</html>
Example2:
<%
String name = request.getParameter("name");
if((name!=null))
{
session.setAttribute("username",name);
}
%>
<a href="session3.jsp">Continue</a>
Example3:
<html>
<head>
www.vandemataramcollege.com Page 87
<title>Welcome to session continued Page</title>
</head>
<body>
<font>Welcome</font> <%= session.getAttribute("username") %>
</body>
</html>
Handling Cookies in JavaServer Pages
How are Cookies Handled in JSP?
Explanation
Cookies and session go hand in hand, the only difference the cookies have is that they are stored
in the browser which is another method to handle a session.
Let us see some examples on handling Cookies in JavaServer Pages:
Example1:
<html>
<body>
<form method = "post" action="cookie2.jsp">
<font>Username<input type = "text" name = "name"></font>
</font><br>
<input type = "submit" name = "submit" value = "submit" >
</form>
</body>
</html>
www.vandemataramcollege.com Page 88
Example2:
<%@ page language="java" import="java.util.*"%>
<%
String name=request.getParameter("name");
Cookie cookie = new Cookie ("name",name);
response.addCookie(cookie);
cookie.setMaxAge(50 * 50); //Time is in Minutes
%>
<a href="cookie3.jsp">Continue</a>
Example3:
<p>Display the value of the Cookie</p>
<%
Cookie[] cookies = request.getCookies();
for (int i=0; i<cookies.length; i++)
{
if(cookies[i].getName().equals("name"))
out.println("Hello"+cookies[i].getValue());
}
%>
In the first example "cookie1.jsp" we get the username using a form. When the form is submitted
it goes to the second page "cookie2.jsp", where the cookie is set an age using the
"cookie.setMaxAge" function. In the third page "cookie3.jsp" the cookie is got using the function
"request.getCookies()" and using a loop the value of the "username" field is displayed.
Removing Cookies:
www.vandemataramcollege.com Page 89
Example:Cookie4.jsp
<%
Cookie cookie = new Cookie( "name", "" );
cookie.setMaxAge( 0 );
%>
In the above example we have created a new instance of cookie with a "null" value and the age
of the cookie is set to "0". This will remove or kill the cookie.
Forms are a very common method of interactions in web sites. JSP makes forms processing
specially easy.
The standard way of handling forms in JSP is to define a "bean". This is not a full Java
bean. You just need to define a class that has a field corresponding to each field in the
form. The class fields must have "setters" that match the names of the form fields. For instance,
let us modify our GetName.html to also collect email address and age.
The new version of GetName.html is
<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
www.vandemataramcollege.com Page 90
To collect this data, we define a Java class with fields "username", "email" and "age" and we
provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter" method is
just a method that starts with "set" followed by the name of the field. The first character of the
field name is upper-cased. So if the field is "email", its "setter" method will be
"setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that the
setters (and getters) must be public.
package user;
public class UserData {
String username;
String email;
int age;
public void setUsername( String value )
{
username = value;
}
public void setEmail( String value )
{
email = value;
}
public void setAge( int value )
{
age = value;
}
public String getUsername() { return username; }
www.vandemataramcollege.com Page 91
public String getEmail() { return email; }
public int getAge() { return age; }
}
The method names must be exactly as shown. Once you have defined the class, compile it and
make sure it is available in the web-server's classpath. The server may also define special folders
where you can place bean classes, e.g. with Blazix you can place them in the "classes" folder. If
you have to change the classpath, the web-server would need to be stopped and restarted if it is
already running. (If you are not familiar with setting/changing classpath, seenotes on changing
classpath.)
Note that we are using the package name user, therefore the file UserData.class must be placed in
a folder named user under the classpath entry.
Now let us change "SaveName.jsp" to use a bean to collect the data.
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>
All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag! The useBean
tag will look for an instance of the "user.UserData" in the session. If the instance is already
there, it will update the old instance. Otherwise, it will create a new instance
of user.UserData (the instance of theuser.UserData is called a bean), and put it in the session.
The setProperty tag will automatically collect the input data, match names against the bean
method names, and place the data in the bean!
Let us modify NextPage.jsp to retrieve the data from bean..
www.vandemataramcollege.com Page 92
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<HTML>
<BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY>
</HTML>
Notice that the same useBean tag is repeated. The bean is available as the variable named "user"
of class "user.UserData". The data entered by the user is all collected in the bean.
top related