[go: up one dir, main page]

0% found this document useful (0 votes)
13 views78 pages

Unit1 Swing

The document provides an overview of Java Swing, a GUI toolkit for Java, detailing its components, methods, and how to create GUI applications using Swing. It explains the hierarchy of Swing classes, commonly used methods, and demonstrates creating frames and various components like buttons, labels, text fields, and more through code examples. Additionally, it briefly introduces working with 2D shapes in JavaFX, outlining the process of creating shapes and their properties.

Uploaded by

Dinesh B.k.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views78 pages

Unit1 Swing

The document provides an overview of Java Swing, a GUI toolkit for Java, detailing its components, methods, and how to create GUI applications using Swing. It explains the hierarchy of Swing classes, commonly used methods, and demonstrates creating frames and various components like buttons, labels, text fields, and more through code examples. Additionally, it briefly introduces working with 2D shapes in JavaFX, outlining the process of creating shapes and their properties.

Uploaded by

Dinesh B.k.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Unit 1: GUI Programming

1.1 Introducing Swing:


Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) –
an API for providing a graphical user interface (GUI) for Java programs.
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications
Java swing components are platform-independent.
Swing components are lightweight.
Swing supports pluggable look and feel.
Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc. Swing follows MVC.
It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in
java.Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

1.1.1 Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

figure 1: hierarchy of java swing API

1
Commonly used Methods of Component class.

The methods of Component class are widely used in java swing that are given below.
Method Description

public void add(Component c) Add a component on another component.

public void setSize(int width,int height) Sets size of the component.

public void setLayout(LayoutManager m) Sets the layout manager for the component.

public void setVisible(boolean b) Sets the visibility of the component. It is by default false

There are two ways to create a frame:


o By creating the object of Frame class (association)
o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.

File: FirstSwingExample.java

import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Output:

2
Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.

File: Simple.java

import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the
position of the button.

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.

3
File: Simple2.java

import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);

add(b);//adding button on frame


setSize(400,500);
setLayout(null); setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}
}

1.2 creating a frame

Java swing components are lightweight, platform-independent, provide powerful components


like tables, scroll panels, buttons, lists, color chooser, etc. In this article, we’ll see how to make
frames using Swings in Java. Ways to create a frame:
Methods:
1. By creating the object of Frame class (association)
2. By extending Frame class (inheritance)
3. Create a frame using Swing inside main()

Way 1: By creating the object of Frame class (association)


In this, we will see how to create a JFrame window by instantiating the JFrame class.

Example:

// Java program to create frames

// using association

import javax.swing.*;

public class test1

JFrame frame;

4
test1()

// creating instance of JFrame with name "first way"

frame=new JFrame("first way");

// creates instance of JButton

JButton button = new JButton("let's see");

button.setBounds(200, 150, 90, 50);

// setting close operation

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// adds button in JFrame

frame.add(button);

// sets 500 width and 600 height

frame.setSize(500, 600);

// uses no layout managers

frame.setLayout(null);

// makes the frame visible

frame.setVisible(true);

public static void main(String[] args)

new test1();

5
Way 2: By extending Frame class (inheritance)
In this example, we will be inheriting JFrame class to create JFrame window and hence it
won’t be required to create an instance of JFrame class explicitly.
Example:

// Java program to create a


// frame using inheritance().
import javax.swing.*
// inheriting JFrame
public class test2 extends JFrame
{
JFrame frame;
test2()
{
setTitle("this is also a title");
// create button
JButton button = new JButton("click");
button.setBounds(165, 135, 115, 55);
// adding button on frame
add(button);
// setting close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new test2();
}
}

Output:

6
Way 3: Create a frame using Swing inside main()
Example 1:

// Java program to create a frame


// using Swings in main().
import javax.swing.*;
public class Swing_example
{
public static void main(String[] args)
{
// creates instance of JFrame
JFrame frame1 = new JFrame();
// creates instance of JButton
JButton button1 = new JButton("click");
JButton button2 = new JButton("again click");
// x axis, y axis, width, height
button1.setBounds(160, 150 ,80, 80);
button2.setBounds(190, 190, 100, 200);
// adds button1 in Frame1
frame1.add(button1);
// adds button2 in Frame1
frame1.add(button2);
// 400 width and 500 height of frame1
frame1.setSize(400, 500) ;
// uses no layout managers
frame1.setLayout(null);
// makes the frame visible
frame1.setVisible(true);
}
}

Output:

7
1.3 Swing components

Swing components are the basic building blocks of an application. We know that Swing is a GUI
widget toolkit for Java. Every application has some basic interactive interface for the user. For
example, a button, check-box, radio-button, text-field, etc. These together form the components
in Swing. Swing components are the interactive elements in a Java application.
Top 13 Components of Swing in Java
Below are the different components of swing in java:

figure 2: Components of Swing in Java

1. JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

JButton class declaration


public class JButton extends AbstractButton implements Accessible
Example
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);

8
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

2. JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.

JLabel class declaration


public class JLabel extends JComponent implements SwingConstants, Accessible
Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);

9
}
}

Output:

3. JTextField

The object of a JTextField class is a text component that allows the editing of a single line text. It
inherits JTextComponent class.

JTextField class declaration


public class JTextField extends JTextComponent implements SwingConstants
Example
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);

10
f.setVisible(true);
}
}

Output:

4. JTextArea

The object of a JTextArea class is a multi line region that displays text. It allows the editing of
multiple line text. It inherits JTextComponent class

JTextArea class declaration


public class JTextArea extends JTextComponent
Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])

11
{
new TextAreaExample();
}
}

Output:

5. JPasswordField

The object of a JPasswordField class is a text component specialized for password entry. It
allows the editing of a single line of text. It inherits JTextField class.
JPasswordField class declaration
public class JPasswordField extends JTextField
Example
import javax.swing.*;
public class PasswordFieldExample {
public static void main(String[] args) {
JFrame f=new JFrame("Password Field Example");
JPasswordField value = new JPasswordField();
JLabel l1=new JLabel("Password:");
l1.setBounds(20,100, 80,30);
value.setBounds(100,100,100,30);
f.add(value); f.add(l1);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

12
6. JCheckBox

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.

JCheckBox class declaration


public class JCheckBox extends JToggleButton implements Accessible
Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}

Output:

13
7. JRadioButton

The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration


public class JRadioButton extends JToggleButton implements Accessible
Example
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:

14
8. JList
The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.

JList class declaration


public class JList extends JComponent implements Scrollable, Accessible
Example:
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}

Output:

15
9. JComboBox
JComboBox class is used to render a dropdown of the list of options.

ComboBox class declaration


public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, Act
ionListe
Example
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:

16
1.4 Working with 2D Shapes
In general, a two dimensional shape can be defined as the geometrical figure that can be drawn
on the coordinate system consist of X and Y planes. However, this is different from 3D shapes in
the sense that each point of the 2D shape always consists of two coordinates (X,Y). Using
JavaFX, we can create 2D shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Cubic
Curve, quad curve, Arc, etc. The class javafx.scene.shape.Shape is the base class for all the shape
classes.

1.4.1 How to create 2D shapes?

As we have mentioned earlier that every shape is represented by a specific class of the
package javafx.scene.shape. For creating a two dimensional shape, the following instructions
need to be followed.

1. Instantiate the respective class :

for example, Rectangle rect = new Rectangle()

2. Set the required properties for the class using instance setter methods: for example,
rect.setX(10);
rect.setY(20);
rect.setWidth(100);
rect.setHeight(100);

3. Add class object to the Group layout: for example,


Group root = new Group();
root.getChildren().add(rect);

The following table consists of the JavaFX shape classes along with their descriptions.
Shape Description

17
Line In general, Line is the geometrical figure which joins two (X,Y) points on 2D coordinate
system. In JavaFX, javafx.scene.shape.Line class needs to be instantiated in order to create
lines.

Rectangle In general, Rectangle is the geometrical figure with two pairs of two equal sides and four
right angles at their joint. In JavaFX, javafx.scene.shape.Rectangle class needs to be
instantiated in order to create Rectangles.

Ellipse In general, ellipse can be defined as a curve with two focal points. The sum of the distances to
the focal points are constant from each point of the ellipse.
In JavaFX. javafx.scene.shape.Ellipse class needs to be instantiated in order to create Ellipse.

Arc Arc can be defined as the part of the circumference of the circle of ellipse.
In JavaFX, javafx.scene.shape.Arc class needs to be instantiated in order to create Arcs.

Circle A circle is the special type of Ellipse having both the focal points at the same location.
In JavaFX, Circle can be created by instantiating javafx.scene.shape.Circle class.

Polygon Polygon is a geometrical figure that can be created by joining the multiple Co-planner
line segments. In JavaFX, javafx.scene.shape. Pollygon class needs to be instantiated in order
to create polygon.

Cubic Curve A Cubic curve is a curve of degree 3 in the XY plane.


In Javafx, javafx.scene.shape.CubicCurve class needs to be instantiated in order to create
Cubic Curves.

Quad Curve A Quad Curve is a curve of degree 2 in the XY plane.


In JavaFX, javafx.scene.shape.QuadCurve class needs to be instantiated in order to
create QuadCurve.

1.5 Java AWT / Color Class


The Color class is a part of Java Abstract Window Toolkit(AWT) package. The Color class
creates color by using the given RGBA values where RGBA stands for RED, GREEN, BLUE,
ALPHA or using HSB value where HSB stands for HUE, SATURATION, BRIcomponents.
The value for individual components RGBA ranges from 0 to 255 or 0.0 to 0.1. The value of
alpha determines the opacity of the color, where 0 or 0.0 stands fully transparent and 255 or
1.0 stands opaque.
Commonly Used Methods In Color Class

Method explanation

brighter() creates a new Color that is a brighter version of this Color.

darker() creates a new Color that is a darker version of this Color.

18
Method explanation

converts a String to an integer and returns the specified


decode(String nm) opaque Color.

determines whether another Color object is equal to this


equals(Object obj) Color.

getAlpha() returns the alpha component in the range 0-255.

getBlue() returns the blue component in the range 0-255 .

getColor(String nm) Finds a color in the system properties.

getColor(String nm, Color v) Finds a color in the system properties.

getColor(String nm, int v) Finds a color in the system properties.

returns the green component in the range 0-255 in the


getGreen() default sRGB space.

returns the red component in the range 0-255 in the default


getRed() sRGB space.

Returns the RGB value representing the color in the default


getRGB() sRGB ColorModel.

getHSBColor(float h, float s, Creates a Color object based on the specified values for the
float b) HSB color model.

getTransparency() returns the transparency mode for this Color.

hashCode() computes the hash code for this Color.

Below programs illustrate the Color class in Java AWT :


import java.awt.*;
import javax.swing.*;
class ColorEx extends JFrame {
// constructor

19
ColorEx()
{
// create a new Color
Color c = Color.yellow;
// create a panel
JPanel p = new JPanel();
p.setBackground(c);
setSize(200, 200);
add(p);
show();

}
// Main Method
public static void main(String args[])
{
ColorEx c = new ColorEx();
}
}
Output :

1.6 Special fonts for text


Introduction
The Font class states fonts, which are used to render text in a visible way.

Class declaration
Following is the declaration for java.awt.Font class:
public class Font
extends Object
implements Serializable

Field
Following are the fields for java.awt.geom.Arc2D class:
 static int BOLD -- The bold style constant.
20
 static int CENTER_BASELINE --The baseline used in ideographic scripts like Chinese,
Japanese, and Korean when laying out text.
 static String DIALOG --A String constant for the canonical family name of the logical
font "Dialog".
 static String DIALOG_INPUT --A String constant for the canonical family name of the
logical font "DialogInput".
 static int HANGING_BASELINE -- The baseline used in Devanigiri and similar scripts
when laying out text.
 static int ITALIC -- The italicized style constant.
 static String SERIF -- A String constant for the canonical family name of the logical font
"Serif".
 protected int size --The point size of this Font, rounded to integer.
 protected int style -- The style of this Font, as passed to the constructor.
 static int TRUETYPE_FONT -- Identify a font resource of type TRUETYPE.
 static int TYPE1_FONT -- Identify a font resource of type TYPE1.
Class methods
S.N. Method & Description

1 boolean canDisplay(char c)
Checks if this Font has a glyph for the specified character.

2 boolean canDisplay(int codePoint)


Checks if this Font has a glyph for the specified character.

5 int canDisplayUpTo(String str)


Indicates whether or not this Font can display a specified String.

6 static Font createFont(int fontFormat, File fontFile)


Returns a new Font using the specified font type and the specified font file.

7 static Font createFont(int fontFormat, InputStream fontStream)


Returns a new Font using the specified font type and input data.

16 Font deriveFont(int style, AffineTransform trans)


Creates a new Font object by replicating this Font object and applying a new style and
transform.

21
17 Font deriveFont(int style, float size)
Creates a new Font object by replicating this Font object and applying a new style and size.

18 Font deriveFont(Map<? extends AttributedCharacterIterator.Attribute,?> attributes)


Creates a new Font object by replicating the current Font object and applying a new set of
font attributes to it.

19 boolean equals(Object obj)


Compares this Font object to the specified Object.

20 protected void finalize()


Disposes the native Font object.

Font Example
Create the following java program using any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AWTGraphicsDemo.java
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {

public AWTGraphicsDemo(){
super("Java AWT Examples");
prepareGUI();
}

public static void main(String[] args){


AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo();
awtGraphicsDemo.setVisible(true);
}

private void prepareGUI(){


setSize(400,400);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
}

22
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
Font plainFont = new Font("Serif", Font.PLAIN, 24);
g2.setFont(plainFont);
g2.drawString("Welcome to TutorialsPoint", 50, 70);
Font italicFont = new Font("Serif", Font.ITALIC, 24);
g2.setFont(italicFont);
g2.drawString("Welcome to TutorialsPoint", 50, 120);
Font boldFont = new Font("Serif", Font.BOLD, 24);
g2.setFont(boldFont);
g2.drawString("Welcome to TutorialsPoint", 50, 170);
Font boldItalicFont = new Font("Serif", Font.BOLD+Font.ITALIC, 24);
g2.setFont(boldItalicFont);
g2.drawString("Welcome to TutorialsPoint", 50, 220);
}
}
output

1.7 Displaying image in swing:


For displaying image, we can use the method drawImage() of Graphics class.

Syntax of drawImage() method:


public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw th
specified image.
Example
import java.awt.*;
import javax.swing.JFrame;
public class MyCanvas extends Canvas{
public void paint(Graphics g) {

23
Toolkit t=Toolkit.getDefaultToolkit();
Image i=t.getImage("p3.gif");
g.drawImage(i, 120,100,this);

}
public static void main(String[] args) {
MyCanvas m=new MyCanvas();
JFrame f=new JFrame();
f.add(m);
f.setSize(400,400);
f.setVisible(true);
}

}
1.8 Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.
Event Handling Example
Create the following java program using any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AwtControlDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showEventDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){

24
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo(){
headerLabel.setText("Control in action: Button");
Button okButton = new Button("OK");
Button submitButton = new Button("Submit");
Button cancelButton = new Button("Cancel");
okButton.setActionCommand("OK");
submitButton.setActionCommand("Submit");
cancelButton.setActionCommand("Cancel");
okButton.addActionListener(new ButtonClickListener());
submitButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if( command.equals( "OK" )) {
statusLabel.setText("Ok Button clicked.");
}
else if( command.equals( "Submit" ) ) {
statusLabel.setText("Submit Button clicked.");
} else {
statusLabel.setText("Cancel Button clicked.");
}
}
}
}
Output:

25
1.9 Event classes
The classes that represent events are at the core of Java’s event handling mechanism. Thus, a
discussion of event handling must begin with the event classes. It is important to understand,
however, that Java defines several types of events and that not all event classes can be discussed
in this chapter. Arguably, the most widely used events at the time of this writing are those
defined by the AWT and those defined by Swing. This chapter focuses on the AWT events.

Events classes and Listeners interfaces


Events classes Listeners interfaces Description
ActionEvent ActionListener This interface is used to receive action events.
MouseListener and
MouseEvent MouseMotionListener This interface is used to receive mouse events.
This interface is used to receive events from the
KeyEvent KeyListener keys.
ItemEvent ItemListener This interface is used to receive element events.
TextEvent TextListener This interface is used to receive text events.
This interface is used to receive adjustment
AdjustmentEvent AdjustmentListener events.
This interface is used to receive events from the
WindowEvent WindowListener window object.
This interface is used to receive events from
ComponentEvent ComponentListener components.
ContainerEvent ContainerListener This interface is used to receive container events.

import javax.swing.*;
import javax.swing.event.*;

26
import java.awt.event.*;
//1st step: Implement ActionListener interface
public class MyJButtonActionListener implements ActionListener
{
private static JTextField text;
public static void main(String[] args)
{
JFrame frame = new JFrame("ActionListener Example");
text = new JTextField();
text.setBounds(45,50,150,20);
JButton btn = new JButton("Click here");
btn.setBounds(70,100,100,30);
MyJButtonActionListener instance = new MyJButtonActionListener();
//2nd step: Register the component with the Listener
btn.addActionListener(instance);
frame.add(btn);
frame.add(text);
frame.setSize(250,250);
frame.setLayout(null);
frame.setVisible(true);
}
//3rd step: Override the method actionPerformed()
public void actionPerformed(ActionEvent e){
text.setText("Welcome to StackHowTo");
}
}
Output

1.10 Java Adapter Classes

Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.

27
using Adapter classes:
o It assists the unrelated classes to work combinedly.
o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages.

1. Java WindowAdapter

In the following example, we are implementing the WindowAdapter class of AWT and one its
methods windowClosing() to close the frame window.
/ importing the necessary libraries
import java.awt.*;
import java.awt.event.*;

public class AdapterExample {


// object of Frame
Frame f;
// class constructor
AdapterExample() {
// creating a frame with the title
f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
}
});
// setting the size, layout and
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}

// main method
public static void main(String[] args) {
new AdapterExample();
}
}

Output:

28
2. Java MouseAdapter
Example

In the following example, we are implementing the MouseAdapter class. The MouseListener
interface is added into the frame to listen the mouse event in the frame.

MouseAdapterExample.java

// importing the necessary libraries


import java.awt.*;
import java.awt.event.*;

// class which inherits the MouseAdapter class


public class MouseAdapterExample extends MouseAdapter {
// object of Frame class
Frame f;
// class constructor
MouseAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Adapter");
// adding MouseListener to the Frame
f.addMouseListener(this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseClicked() method of the MouseAdapter class
public void mouseClicked (MouseEvent e) {
// creating the Graphics object and fetching them from the Frame object using getGraphics() met
hod
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.BLUE);

29
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 30, 30);
}
// main method
public static void main(String[] args) {
new MouseAdapterExample();
}
}
Output:

3. Java MouseMotionAdapter

In the following example, we are implementing the MouseMotionAdapter class and its different
methods to listen to the mouse motion events in the Frame window.

MouseMotionAdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the MouseMotionAdapter class
public class MouseMotionAdapterExample extends MouseMotionAdapter {
// object of Frame class
Frame f;
// class constructor
MouseMotionAdapterExample() {
// creating the frame with the title
f = new Frame ("Mouse Motion Adapter");
// adding MouseMotionListener to the Frame
f.addMouseMotionListener (this);
// setting the size, layout and visibility of the frame
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
// overriding the mouseDragged() method
public void mouseDragged (MouseEvent e) {

30
// creating the Graphics object and fetching them from the Frame object using getGraphics() met
hod
Graphics g = f.getGraphics();
// setting the color of graphics object
g.setColor (Color.ORANGE);
// setting the shape of graphics object
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}

Output:

4. Java KeyAdapter

In the following example, we are implementing the KeyAdapter class and its method.

KeyAdapterExample.java
// importing the necessary libraries
import java.awt.*;
import java.awt.event.*;
// class which inherits the KeyAdapter class
public class KeyAdapterExample extends KeyAdapter {
// creating objects of Label, TextArea and Frame
Label l;
TextArea area;
Frame f;
// class constructor
KeyAdapterExample() {
// creating the Frame with title
f = new Frame ("Key Adapter");
// creating the Label
31
l = new Label();
// setting the location of label
l.setBounds (20, 50, 200, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding KeyListener to text area
area.addKeyListener(this);
// adding the label and text area to frame
f.add(l);
f.add(area);
// setting the size, layout and visibility of frame
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
// overriding the keyReleased() method
public void keyReleased (KeyEvent e) {
// creating the String object to get the text fromTextArea
String text = area.getText();
// splitting the String into words
String words[] = text.split ("\\s");
// setting the label text to print the number of words and characters of given string
l.setText ("Words: " + words.length + " Characters:" + text.length());
}
// main method
public static void main(String[] args) {
new KeyAdapterExample();
}
}

Output:

32
1.10.1 MVC Design Pattern

The Model View Controller (MVC) design pattern specifies that an application consist of a
data model, presentation information, and control information. The pattern requires that each
of these be separated into different objects.
MVC is more of an architectural pattern, but not for complete application. MVC mostly relates
to the UI / interaction layer of an application.
 The Model contains only the pure application data, it contains no logic describing how to
present the data to a user.
 The View presents the model’s data to the user. The view knows how to access the model’s
data, but it does not know what this data means or what the user can do to manipulate it.
 The Controller exists between the view and the model. It listens to events triggered by the
view (or another external source) and executes the appropriate reaction to these events. In
most cases, the reaction is to call a method on the model. Since the view and the model are
connected through a notification mechanism, the result of this action is then automatically
reflected in the view.
In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the user
requests are processed as follows:

33
Figure 3: MVC Design Pattern

Advantages

 Multiple developers can work simultaneously on the model, controller and views.
 MVC enables logical grouping of related actions on a controller together. The views for a
specific model are also grouped together.
 Models can have multiple views.

Disadvantages
 The framework navigation can be complex because it introduces new layers of abstraction
and requires users to adapt to the decomposition criteria of MVC.
 Knowledge on multiple technologies becomes the norm. Developers using MVC need to be
skilled in multiple technologies .

Example of MVC Design Pattern

// class that represents model


public class Employee {

// declaring the variables


private String EmployeeName;
private String EmployeeId;
private String EmployeeDepartment;

// defining getter and setter methods


public String getId() {

34
return EmployeeId;
}

public void setId(String id) {


this.EmployeeId = id;
}

public String getName() {


return EmployeeName;
}

public void setName(String name) {


this.EmployeeName = name;
}

public String getDepartment() {


return EmployeeDepartment;
}

public void setDepartment(String Department) {


this.EmployeeDepartment = Department;
}

// class which represents the view


public class EmployeeView {

// method to display the Employee details


public void printEmployeeDetails (String EmployeeName, String EmployeeId, String Employee
Department){
System.out.println("Employee Details: ");
System.out.println("Name: " + EmployeeName);
System.out.println("Employee ID: " + EmployeeId);

35
System.out.println("Employee Department: " + EmployeeDepartment);
}
}
// class which represent the controller
public class EmployeeController {

// declaring the variables model and view


private Employee model;
private EmployeeView view;

// constructor to initialize
public EmployeeController(Employee model, EmployeeView view) {
this.model = model;
this.view = view;
}

// getter and setter methods


public void setEmployeeName(String name){
model.setName(name);
}

public String getEmployeeName(){


return model.getName();
}

public void setEmployeeId(String id){


model.setId(id);
}

public String getEmployeeId(){


return model.getId();
}

public void setEmployeeDepartment(String Department){

36
model.setDepartment(Department);
}

public String getEmployeeDepartment(){


return model.getDepartment();
}

// method to update view


public void updateView() {
view.printEmployeeDetails(model.getName(), model.getId(), model.getDepartment
());
}
}

// main class
public class MVCMain {
public static void main(String[] args) {

// fetching the employee record based on the employee_id from the database
Employee model = retriveEmployeeFromDatabase();

// creating a view to write Employee details on console


EmployeeView view = new EmployeeView();

EmployeeController controller = new EmployeeController(model, view);

controller.updateView();

//updating the model data


controller.setEmployeeName("Nirnay");
System.out.println("\n Employee Details after updating: ");

controller.updateView();
}

37
private static Employee retriveEmployeeFromDatabase(){
Employee Employee = new Employee();
Employee.setName("Anu");
Employee.setId("11");
Employee.setDepartment("Salesforce");
return Employee;
}
}

Output:
Employee Details:
Name: Anu
Employee ID: 11
Employee Department: Salesforce

Employee Details after updating:


Name: Nirnay
Employee ID: 11
Employee Department: Salesforce

1.10.2 Layout Managements

The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

1. Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:
1. public static final int NORTH

38
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java

import java.awt.*;
import javax.swing.*;

public class Border


{
JFrame f;
Border()
{
f = new JFrame();

// creating buttons
JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER

f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction


f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

Output:

39
2. Java FlowLayout

The Java FlowLayout class is used to arrange the components in a line, one after another (in a
flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Example of FlowLayout class: Using FlowLayout() constructor
FileName: FlowLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample


{

40
JFrame frameObj;

// constructor
FlowLayoutExample()
{
// creating a frame object
frameObj = new JFrame();

// creating the buttons


JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");

// adding the buttons to frame


frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
frameObj.add(b9); frameObj.add(b10);

// parameter less constructor is used


// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());

frameObj.setSize(300, 300);
frameObj.setVisible(true);
}

// main method
public static void main(String argvs[])
{
new FlowLayoutExample();
}
}

41
Output:

3.Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.
Example of GridLayout class: Using GridLayout() Constructor
The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.
FileName: GridLayoutExample.java
// import statements
import java.awt.*;
import javax.swing.*;

public class GridLayoutExample


{
JFrame frameObj;

// constructor
GridLayoutExample()
{
frameObj = new JFrame();

// creating 9 buttons
JButton btn1 = new JButton("1");

42
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");

// adding buttons to the frame


// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);

// setting the grid layout using the parameterless constructor


frameObj.setLayout(new GridLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}

// main method
public static void main(String argvs[])
{
new GridLayoutExample();
}
}

Output:

43
4.Java CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known as
CardLayout.
Constructors of CardLayout Class
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
Commonly Used Methods of CardLayout Class
o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the given
container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card
with the given name.

Example of CardLayout Class: Using Default Constructor


The following program uses the next() method to move to the next card of the container.
FileName: CardLayoutExample1.java
// import statements
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class CardLayoutExample1 extends JFrame implements ActionListener


{

CardLayout crd;

// button variables to hold the references of buttons


JButton btn1, btn2, btn3;
Container cPane;

// constructor of the class


CardLayoutExample1()
{

cPane = getContentPane();

//default constructor used


// therefore, components will
// cover the whole area
crd = new CardLayout();

44
cPane.setLayout(crd);

// creating the buttons


btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");

// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);

cPane.add("a", btn1); // first card is the button btn1


cPane.add("b", btn2); // first card is the button btn2
cPane.add("c", btn3); // first card is the button btn3

}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon clicking
crd.next(cPane);
}

// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();

// size is 300 * 300


crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Output:

45
When the button named apple is clicked, we get

When the boy button is clicked, we get

46
Again, we reach the first card of the container if the cat button is clicked, and the cycle
continues.

5.Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
baseline.
The components may not be of the same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display area.
Each component associates an instance of GridBagConstraints. With the help of the constraints
object, we arrange the component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine the component's size.
GridBagLayout components are also arranged in the rectangular grid but can have many
different sizes and can occupy multiple rows or columns.
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4. import javax.swing.*;
5. public class GridBagLayoutExample extends JFrame{
6. public static void main(String[] args) {
7. GridBagLayoutExample a = new GridBagLayoutExample();
8. }
9. public GridBagLayoutExample() {
10. GridBagLayoutgrid = new GridBagLayout();
11. GridBagConstraints gbc = new GridBagConstraints();
12. setLayout(grid);

47
13. setTitle("GridBag Layout Example");
14. GridBagLayout layout = new GridBagLayout();
15. this.setLayout(layout);
16. gbc.fill = GridBagConstraints.HORIZONTAL;
17. gbc.gridx = 0;
18. gbc.gridy = 0;
19. this.add(new Button("Button One"), gbc);
20. gbc.gridx = 1;
21. gbc.gridy = 0;
22. this.add(new Button("Button two"), gbc);
23. gbc.fill = GridBagConstraints.HORIZONTAL;
24. gbc.ipady = 20;
25. gbc.gridx = 0;
26. gbc.gridy = 1;
27. this.add(new Button("Button Three"), gbc);
28. gbc.gridx = 1;
29. gbc.gridy = 1;
30. this.add(new Button("Button Four"), gbc);
31. gbc.gridx = 0;
32. gbc.gridy = 2;
33. gbc.fill = GridBagConstraints.HORIZONTAL;
34. gbc.gridwidth = 2;
35. this.add(new Button("Button Five"), gbc);
36. setSize(300, 300);
37. setPreferredSize(getSize());
38. setVisible(true);
39. setDefaultCloseOperation(EXIT_ON_CLOSE);
40.
41. }
42.
43. }
Output:

48
6.java BoxLayout
The Java BoxLayout class is used to arrange the components either vertically or horizontally.
For this purpose, the BoxLayout class provides four constants.
1. public static final int X_AXIS: Alignment of the components are horizontal from left to
right.
2. public static final int Y_AXIS: Alignment of the components are vertical from top to
bottom.
3. public static final int LINE_AXIS: Alignment of the components is similar to the way
words are aligned in a line, which is based on the ComponentOrientation property of the
container.
4. public static final int PAGE_AXIS: Alignment of the components is similar to the way
text lines are put on a page, which is based on the ComponentOrientation property of the
container.
Example of BoxLayout class with Y-AXIS:
FileName: BoxLayoutExample1.java
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class BoxLayoutExample1 extends Frame {
5. Button buttons[];
6.
7. public BoxLayoutExample1 () {
8. buttons = new Button [5];
9.
10. for (int i = 0;i<5;i++) {
11. buttons[i] = new Button ("Button " + (i + 1));
12. // adding the buttons so that it can be displayed
13. add (buttons[i]);
14. }
15. // the buttons will be placed horizontally
16. setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
17. setSize(400,400);
18. setVisible(true);
19. }
20. // main method
21. public static void main(String args[]){
22. BoxLayoutExample1 b=new BoxLayoutExample1();
23. }
24. }

Output:

49
7.GroupLayout
GroupLayout groups its components and places them in a Container hierarchically. The
grouping is done by instances of the Group class.
Group is an abstract class, and two concrete classes which implement this Group class are
SequentialGroup and ParallelGroup.
SequentialGroup positions its child sequentially one after another whereas ParallelGroup aligns
its child on top of each other.
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4. public class GroupExample {
5. public static void main(String[] args) {
6. JFrame frame = new JFrame("GroupLayoutExample");
7. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
8. Container contentPanel = frame.getContentPane();
9. GroupLayout groupLayout = new GroupLayout(contentPanel);
10.
11. contentPanel.setLayout(groupLayout);
12.
13. JLabel clickMe = new JLabel("Click Here");
14. JButton button = new JButton("This Button");
15.
16. groupLayout.setHorizontalGroup(
17. groupLayout.createSequentialGroup()
18. .addComponent(clickMe)
19. .addGap(10, 20, 100)

50
20. .addComponent(button));
21. groupLayout.setVerticalGroup(
22. groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
23. .addComponent(clickMe)
24. .addComponent(button));
25. frame.pack();
26. frame.setVisible(true);
27. }
28. }
Output:

8.ScrollPaneLayout
The layout manager is used by JScrollPane. JScrollPaneLayout is responsible for nine
components: a viewport, two scrollbars, a row header, a column header, and four "corner"
components.
1. import javax.swing.ImageIcon;
2. import javax.swing.JFrame;
3. import javax.swing.JLabel;
4. import javax.swing.JScrollPane;
5. public class ScrollPaneDemo extends JFrame
6. {
7. public ScrollPaneDemo() {
8. super("ScrollPane Demo");
9. ImageIcon img = new ImageIcon("child.png");
10.
11. JScrollPane png = new JScrollPane(new JLabel(img));
12.
13. getContentPane().add(png);
14. setSize(300,250);
15. setVisible(true);
16. }
17.
18. public static void main(String[] args) {
19. new ScrollPaneDemo();
20. }
21. }
Output:

51
9.SpringLayout Class
A SpringLayout class in AWT(Abstract Window Toolkit) laid out of the children to its
associated container, according to a set of Layout constraints. Each constraint is represented by a
Spring object which controls the vertical or horizontal distance between two component edges.
SpringLayout(): Used to constructs a new SpringLayout class.

Commonly Used Methods:


 void addLayoutComponent(Component com, Object cons): If constraints is an instance
of SpringLayout.Constraints, associates the constraints with the specified component.
 getLayoutAlignmentX(Container c): Used to returns 0.5f (centered).
 getLayoutAlignmentY(Container c): Used to returns 0.5f (centered).
 getConstraint((String edgeName, Component c): Returns the spring controlling the
distance between the specified edge of the component and the top or left edge of its parent.
 getConstraint(Component c): Returns the constraints for the specified component.
 layoutContainer(Container parent): Used to Lays out the specified container.
Example
// Java program to show Example of SpringLayout.
// in java. Importing different Package.
import java.awt.*;
import javax.swing.*;

// construct a class Springclassdemo


public class Springclassdemo {

// Main Method
public static void main(String[] arguments)
{

// main window
// Function to set the default look
// and feel decorated status of JFrame.

52
JFrame.setDefaultLookAndFeelDecorated(true);

// Creating Object of "JFrame" class


JFrame frame = new JFrame("SpringLayoutExample Example");

// Function to set the default


// close operation status of JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Function to set the


// size status of JFrame
frame.setSize(300, 200);

// to get the content pane


Container content = frame.getContentPane();

// Creating Object of "SpringLayout" class


SpringLayout layout = new SpringLayout();

// to set the layout class


frame.setLayout(layout);

// Initialization of object
// "b1" of JButton class.
Component b1 = new JButton("GEEKS");

// Initialization of object
// "b2" of JButton class.
Component b2 = new JButton("GFG");

// Initialization of object
// "b3" of JButton class.
Component b3 = new JButton("JAVA");

// Initialization of object
// "b4" of JButton class.
Component b4 = new JButton("Sudo Placement");

// Adding the JButton "b1" on frame


frame.add(b1);

// Adding the JButton "b2" on frame


frame.add(b2);

// Adding the JButton "b3" on frame


frame.add(b3);

53
// Adding the JButton "b4" on frame
frame.add(b4);

// It is used to put the layout


// constraint in JFrame using
// springLayout class on b1 JButton
layout.putConstraint(SpringLayout.WEST, b1,
25, SpringLayout.WEST, content);

layout.putConstraint(SpringLayout.NORTH, b1,
10, SpringLayout.NORTH, content);

// It is used to put the layout


// constraint in JFrame using
// springLayout class on b2 JButton
layout.putConstraint(SpringLayout.WEST, b2,
50, SpringLayout.WEST, content);

layout.putConstraint(SpringLayout.NORTH, b2,
10, SpringLayout.SOUTH, b1);

// It is used to put the layout


// constraint in JFrame using
// springLayout class on b3 JButton
layout.putConstraint(SpringLayout.WEST, b3,
75, SpringLayout.WEST, content);

layout.putConstraint(SpringLayout.NORTH, b3,
10, SpringLayout.SOUTH, b2);

// It is used to put the layout


// constraint in JFrame using
// springLayout class on b4 JButton
layout.putConstraint(SpringLayout.WEST, b4,
15, SpringLayout.EAST, b1);

layout.putConstraint(SpringLayout.NORTH, b4,
10, SpringLayout.NORTH, content);

// Function to set the


// visible status of JFrame
frame.setVisible(true);
}
}

54
UNIT 2 Database Programming

2.1 Design of JDBC


Java Database Connectivity (JDBC) is an Application Programming Interface (API), from Sun
microsystem that is used by the Java application to communicate with the relational databases
from different vendors. JDBC and database drivers work in tandem to access spreadsheets and
databases. Design of JDBC defines the components of JDBC, which is used for connecting to the
database. The JDBC classes are contained in the Java Package java.sql and javax.sql.

2.2 JDBC Architecture


The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −
 JDBC API − This provides the application-to-JDBC Manager connection.
 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

Figure 2.1 Architecture of JDBC

2.4 Common JDBC Components


The JDBC API provides the following interfaces and classes −
 DriverManager − This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
 Driver − This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,

55
which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
 Connection − This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
 Statement − You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
 ResultSet − These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its
data.
 SQLException − This class handles any errors that occur in a database application.

2.5 JDBC Drivers


JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. For
example, using JDBC drivers enable you to open database connections and to interact with it by
sending SQL or database commands then receiving results with Java.

2.5.1JDBC Drivers Types


JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below –

Type 1 − JDBC-ODBC Bridge Driver


In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when no
other alternative is available.

56
Figure 2.2 JDBC-ODBC Bridge Driver

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2 − JDBC-Native API


In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.
If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.

Figure 2.3 JDBC-Native API

Type 3 − JDBC-Net pure Java


In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket

57
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.

Figure 2.4 JDBC-Net pure Java

Type 4 − 100% Pure Java


In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

Figure 2.5 :100% Pure Java

2.6 Typical uses of JDBC


JDBC, ODBC API was the database API to connect and execute the query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and

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

We can use JDBC API to handle database using Java program and can perform the following
activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

2.7 Structured Query Language


SQL (Structured Query Language) is used to perform operations on the records stored in the
database, such as updating records, inserting records, deleting records, creating and modifying
database tables, views, etc.
Why SQL?
Nowadays, SQL is widely used in data science and analytics. Following are the reasons which
explain why it is widely used:

o The basic use of SQL for data professionals and SQL users is to insert, update, and delete
the data from the relational database.
o SQL allows the data professionals and users to retrieve the data from the relational
database management systems.
o It also helps them to describe the structured data.
o It allows SQL users to create, drop, and manipulate the database and its tables.
o It also helps in creating the view, stored procedure, and functions in the relational
database.
o It allows you to define the data and modify that stored data in the relational database.
o It also allows SQL users to set the permissions or constraints on table columns, views,
and stored procedures.

2.7.1 Process of SQL


When we are executing the command of SQL on any Relational database management system,
then the system automatically finds the best routine to carry out our request, and the SQL engine
determines how to interpret that particular command.

Structured Query Language contains the following four components in its process:

o Query Dispatcher
o Optimization Engines
o Classic Query Engine

59
o SQL Query Engine, etc.

A classic query engine allows data professionals and users to maintain non-SQL queries. The
architecture of SQL is shown in the following diagram:

Figure2.6 : architecture of SQLdiagram

2.7.2 Some SQL Commands


The SQL commands help in creating and managing the database. The most common SQL
commands which are highly used are mentioned below:

1. CREATE command : This command helps in creating the new database, new table, table
view, and other objects of the database.
2. UPDATE command : This command helps in updating or changing the stored data in the
database.
3. DELETE command : This command helps in removing or erasing the saved records from
the database tables. It erases single or multiple tuples from the tables of the database.
4. SELECT command : This command helps in accessing the single or multiple rows from
one or multiple tables of the database. We can also use this command with the WHERE
clause.

60
5. DROP command: This command helps in deleting the entire table, table view, and other
objects from the database.
6. INSERT command : This command helps in inserting the data or records into the
database tables. We can easily insert the records in single as well as multiple rows of the
table.

Advantages of SQL
Following are the best advantages or benefits of Structured Query Language:

1. No programming needed

SQL does not require a large number of coding lines for managing the database systems. We can
easily access and maintain the database by using simple SQL syntactical rules. These simple
rules make the SQL user-friendly.

2. High-Speed Query Processing

A large amount of data is accessed quickly and efficiently from the database by using SQL
queries. Insertion, deletion, and updation operations on data are also performed in less time.

3. Standardized Language
SQL follows the long-established standards of ISO and ANSI, which offer a uniform
platform across the globe to all its users.

4. Portability

The structured query language can be easily used in desktop computers, laptops, tablets, and
even smartphones. It can also be used with other applications according to the user's
requirements.

5. Interactive language

We can easily learn and understand the SQL language. We can also use this language for
communicating with the database because it is a simple query language. This language is also
used for receiving the answers to complex queries in a few seconds.

6. More than one Data View

The SQL language also helps in making the multiple views of the database structure for the
different database users.

Disadvantages of SQL
With the advantages of SQL, it also has some disadvantages, which are as follows:

61
1. Cost

The operation cost of some SQL versions is high. That's why some programmers cannot use the
Structured Query Language.

2. Interface is Complex

Another big disadvantage is that the interface of Structured query language is difficult, which
makes it difficult for SQL users to use and manage it.

3. Partial Database control

The business rules are hidden. So, the data professionals and users who are using this query
language cannot have full database control.

2.8 JDBC configuration


JDBC configuration involves setting up a JDBC driver, defining a JDBC connection
pool, and registering the JDBC resources used by your application. A JDBC driver
must be configured in the classpath of the web server before you can exercise
applications that use JDBC.
Java Database Connectivity with 5 Steps
There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is used to dynamically loa
the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

1. Class.forName("oracle.jdbc.driver.OracleDriver");

62
2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException

1. 2) public static Connection getConnection(String url,String name,String password)


2. throws SQLException
Example to establish connection with the Oracle database

1Connection con=DriverManager.getConnection(

1. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The object of statement
responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object

Statement stmt=con.createStatement();

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the database. This method return
the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

63
Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");


2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The close() method
Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();

Example
// Java Program to Establish Connection in JDBC

// Importing database
importjava.sql.*;
// Importing required classes
importjava.util.*;

// Main class
class Main {

// Main driver method


public static void main(String a[])
{

// Creating the connection using Oracle DB


// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";

// Usernamer and password to access DB


// Custom initialization
String user = "system";
64
String pass = "12345";

// Entering the data


Scanner k = new Scanner(System.in);

System.out.println("enter name");
String name = k.next();

System.out.println("enter roll no");


int roll = k.nextInt();

System.out.println("enter class");
String cls = k.next();

// Inserting data using SQL query


String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";

// Connection class object


Connection con = null;

// Try block to check for exceptions


try {

// Registering drivers
DriverManager.registerDriver(
new oracle.jdbc.OracleDriver());

// Reference to connection interface


con = DriverManager.getConnection(url, user,pass);

// Creating a statement
Statement st = con.createStatement();

// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println(
"inserted successfully : " + sql);
else
System.out.println("insertion failed");

// Closing the connections


con.close();
}

65
// Catch block to handle exceptions
catch (Exception ex) {
// Display message when exceptions occurs
System.err.println(ex);
}
}
}
Output:

2.10 Statements in JDBC


The statement interface is used to create SQL basic statements in Java it provides methods to
execute queries with the database. There are different types of statements that are used in
JDBC as follows:
 Create Statement
 Prepared Statement
 Callable Statement
1. Create a Statement: From the connection interface, you can create the object for this
interface. It is generally used for general–purpose access to databases and is useful while using
static SQL statements at runtime.
Syntax:
Statement statement = connection.createStatement();
Example
// Java Program illustrating Create Statement in JDBC

// Importing Database(SQL) classes


import java.sql.*;

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{

66
// Try block to check if any exceptions occur
try {

// Step 2: Loading and registering drivers

// Loading driver using forName() method


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

// Registering driver using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 3: Create a statement


Statement statement = con.createStatement();
String sql = "select * from people";

// Step 4: Execute the query


ResultSet result = statement.executeQuery(sql);

// Step 5: Process the results

// Condition check using hasNext() method which


// holds true till there is single element
// remaining in List
while (result.next()) {

// Print name an age


System.out.println(
"Name: " + result.getString("name"));
System.out.println(
"Age:" + result.getString("age"));
}
}

// Catching database exceptions if any


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catching generic ClassNotFoundException if any


catch (ClassNotFoundException e) {

// Print and display the line number


// where exception occurred

67
e.printStackTrace();
}
}
}

Output:

2.Prepared Statement
Prepared Statement represents a recompiled SQL statement, that can be executed many
times. This accepts parameterized SQL queries. In this, “?” is used instead of the parameter,
one can pass the parameter dynamically by using the methods of PREPARED STATEMENT
at run time.

Example
// Java Program illustrating Prepared Statement in JDBC

// Step 1: Importing DB(SQL here) classes


import java.sql.*;
// Importing Scanner class to
// take input from the user
import java.util.Scanner;

// Main clas
class GFG {

// Main driver method


public static void main(String[] args)
{
// try block to check for exceptions
try {

// Step 2: Establish a connection

// Step 3: Load and register drivers


68
// Loading drivers using forName() method
Class.forName("com.mysql.cj.jdbc.Driver");

// Scanner class to take input from user


Scanner sc = new Scanner(System.in);

// Display message for ease for user


System.out.println(
"What age do you want to search?? ");

// Reading age an primitive datatype from user


// using nextInt() method
int age = sc.nextInt();

// Registering drivers using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 4: Create a statement


PreparedStatement ps = con.prepareStatement(
"select name from world.people where age = ?");

// Step 5: Execute the query


ps.setInt(1, age);
ResultSet result = ps.executeQuery();

// Step 6: Process the results

// Condition check using next() method


// to check for element
while (result.next()) {

// Print and display elements(Names)


System.out.println("Name : "
+ result.getString(1));
}

// Step 7: Closing the connections


// (Optional but it is recommended to do so)
}

// Catch block to handle database exceptions


catch (SQLException e) {

// Display the DB exception if any

69
System.out.println(e);
}

// Catch block to handle class exceptions


catch (ClassNotFoundException e) {

// Print the line number where exception occurred


// using printStackTrace() method if any
e.printStackTrace();
}
}
}
Output:

3.Callable Statement
Callable Statement are stored procedures which are a group of statements that we
compile in the database for some task, they are beneficial when we are dealing with
multiple tables with complex scenario & rather than sending multiple queries to the
database, we can send the required data to the stored procedure & lower the logic
executed in the database server itself. The Callable Statement interface provided by
JDBC API helps in executing stored procedures.
Syntax: To prepare a CallableStatement
CallableStatement cstmt = con.prepareCall("{call Procedure_name(?, ?}");

// Java Program illustrating Callable Statement in JDBC

// Step 1: Importing DB(SQL) classes


import java.sql.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Try block to check if any exceptions occurs
try {

// Step 2: Establish a connection

70
// Step 3: Loading and registering drivers

// Loading driver using forName() method


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

// Registering driver using DriverManager


Connection con = DriverManager.getConnection(
"jdbc:mysql:///world", "root", "12345");

// Step 4: Create a statement


Statement s = con.createStatement();

// Step 5: Execute the query


// select * from people

CallableStatement cs
= con.prepareCall("{call peopleinfo(?,?)}");
cs.setString(1, "Bob");
cs.setInt(2, 64);
cs.execute();
ResultSet result
= s.executeQuery("select * from people");

// Step 6: Process the results

// Condition check using next() method


// to check for element
while (result.next()) {

// Print and display elements (Name and Age)


System.out.println("Name : "
+ result.getString(1));
System.out.println("Age : "
+ result.getInt(2));
}
}

// Catch statement for DB exceptions


catch (SQLException e) {

// Print the exception


System.out.println(e);
}

// Catch block for generic class exceptions


catch (ClassNotFoundException e) {

71
// Print the line number where exception occurred
e.printStackTrace();
}
}
}

Output:

2.10.1 Query Execution

To execute a query, call an execute method from Statement such as the following:

 execute: Returns true if the first object that the query returns is a ResultSet object. Use
this method if the query could return one or more ResultSet objects. Retrieve
the ResultSet objects returned from the query by repeatedly
calling Statement.getResultSet.
 executeQuery: Returns one ResultSet object.
 executeUpdate: Returns an integer representing the number of rows affected by the SQL
statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL
statements.

2.10.2 Scrollable and Update ResultSet:

2.10.2.1Scrollable ResultSet:
A scrollable ResultSet is one which allows us to retrieve the data in forward direction as well as
backward direction but no updations are allowed. In order to make the non-scrollable ResultSet
as scrollable ResultSet as scrollable ResultSet we must use the following createStatement which
is present in Connection interface.

72
Type represents type of scrollability and Mode represents either read only or updatable. The
value of Type and value of Mode are present in ResultSet interface as constant data members and
they are:

int Type int Mode

TYPE_FORWARD_ONLY - 1 CONCUR_READ_ONLY - 3

TYPE_SCROLL_INSENSITIVE - 2

Example Write a java program which illustrates the concept of Scrollable Result set?
import java.sql.*;

class ScrollResultSet {

public static void main(String[] args) {


try {
Class.forName("Sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DRIVERS LOADED...");
Connection con = DriverManager.getConnection("jdbc:odbc:oradsn", "scott", "tiger");
System.out.println("CONNECTION ESTABLISHED...");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSe
t.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("select * from emp");
System.out.println("RECORDS IN THE TABLE...");
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
rs.first();
System.out.println("FIRST RECORD...");
System.out.println(rs.getInt(1) + " " + rs.getString(2));
rs.absolute(3);
System.out.println("THIRD RECORD...");
System.out.println(rs.getInt(1) + " " + rs.getString(2));

73
rs.last();
System.out.println("LAST RECORD...");
System.out.println(rs.getInt(1) + " " + rs.getString(2));
rs.previous();
rs.relative(-1);
System.out.println("FIRST RECORD...");
System.out.println(rs.getInt(1) + " " + rs.getString(2));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}// main
};// ScrollResultSet

2.10.2.1 UpdateResultSet
Whenever we create a ResultSet object which never allows us to update the database through
ResultSet object and it allows retrieving the data only in forward direction. Such type of
ResultSet is known as non-updatable and non-scrollable ResultSet.
In order to make the ResultSet object as updatable and scrollable we must use the following
constants which are present in ResultSet interface.

int Type int Mode

TYPE_SCROLL_SENSITIVE CONCUR_UPDATABLE

The above two constants must be specified while we are creating Statement object by using the
following method:

For example: Write a java program which illustrates the concept of updatable ResultSet?

import java.sql.*;

74
class UpdateResultSet {

public static void main(String[] args) {


try {
Class.forName("Sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("DRIVERS LOADED...");
Connection con = DriverManager.getConnection("jdbc:odbc:oradsn", "scott", "tiger");
System.out.println("CONNECTION ESTABLISHED...");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.
CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from emp1");
rs.next();
rs.updateInt(2, 8000);
rs.updateRow();
System.out.println("1 ROW UPDATED...");
rs.moveToInsertRow();
rs.updateInt(1, 104);
rs.updateInt(2, 2000);
rs.insertRow();
System.out.println("1 ROW INSERTED...");
rs.absolute(2);
rs.deleteRow();
System.out.println("1 ROW DELETED...");
con.close();
} catch (Exception e) {

e.printStackTrace();
}
}// main
};// UpdateResultSet

2.10.3 Row sets


A RowSet is an object that encapsulates a set of rows from either java Database Connectivity
(JDBC) result sets or tabular data sources.
RowSets support component-based development models like JavaBeans, with a standard set of
properties and an event notification mechanism.
It is introduced in JDK5. A JDBC RowSet provides a way to store the data in tabular form. It
makes the data more flexible and easier than a ResultSet.
RowSets are classified into five categories based on how they are implemented which are listed
namely as below:

75
 JdbcRowSet
 CachedRowSet
 WebRowSet
 FilteredRowSet
 JoinRowSet

Example
// Java Program to Illustrate RowSet in JDBC

// Importing database
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;

// Main class
class RowSetDemo {

// Main driver method


public static void main(String args[])
{

// Try block to check for exceptions


try {

// Loading and registering drivers


Class.forName(
"oracle.jdbc.driver.OracleDriver");

76
// Creating a RowSet
JdbcRowSetrowSet = RowSetProvider.newFactory()
.createJdbcRowSet();

// Setting URL, username, password


rowSet.setUrl(
"jdbc:oracle:thin:@localhost:1521:xe");
rowSet.setUsername("root");
rowSet.setPassword("pass");

// Creating a query
rowSet.setCommand("select * from Student");

// Executing the query


rowSet.execute();

// Processign the results


while (rowSet.next()) {

// Print and display commands


System.out.println("RollNo: "
+ rowSet.getInt(1));
System.out.println("Name: "
+ rowSet.getString(2));
System.out.println("Marks: "
+ rowSet.getString(3));
}
}

77
// Catch block to handle the exceptions
catch (Exception e) {

// Print and display the exception along with


// line number using printStackTrace() method
e.printStackTrace();
}
}
}
Output:
RollNo: 1
Name: jack
Marks: 92
RollNo: 2
Name: jenny
Marks: 90
RollNo: 3
Name: mark
Marks: 80
RollNo: 4
Name: joe
Marks: 82

78

You might also like