0% found this document useful (0 votes)
27 views93 pages

Sycs Java Unit-2

Uploaded by

Raj pankaj
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)
27 views93 pages

Sycs Java Unit-2

Uploaded by

Raj pankaj
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/ 93

UNIT-2 SYCS-JAVA

CHAPTER-1
Collection Framework
****************************************************************
Introduction

The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

o It provides readymade architecture.


o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

java.util Package interfaces


It contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

List
A list in Java is a sequence of elements according to an order. The List interface of java.util
package is the one that implements this sequence of objects ordered in a particular fashion
called List.
Just like arrays, the list elements can also be accessed using indices with the first index
starting at 0. The index indicates a particular element at index ‘i’ i.e. it is i elements away
from the beginning of the list.

Some of the characteristics of the list in Java include:


• Lists can have duplicate elements.
• The list can also have ‘null’ elements.
• Lists support generics i.e. you can have generic lists.
• You can also have mixed objects (objects of different classes) in the same list.
• Lists always preserve insertion order and allow positional access.

Create & Declare List

We have already stated that List is an interface and is implemented by classes like
ArrayList, Stack, Vector and LinkedList. Hence you can declare and create instances of
the list in any one of the following ways:

List linkedlist = new LinkedList();


List arrayList = new ArrayList();
List vec_list = new Vector();
List stck_list = new Stack();
As shown above, you can create a list with any of the above classes and then initialize these
lists with values. From the above statements, you can make out that the order of elements
will change depending on the class used for creating an instance of the list.

Initialize Java List

Using List.add()
As already mentioned, as the list is just an interface it cannot be instantiated. But we can
instantiate classes that implement this interface. Therefore to initialize the list classes, you
can use their respective add methods which is a list interface method but implemented by
each of the classes.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

If you instantiate a linked list class as below:


List<Integer> llist = new LinkedList<Integer> ();
Then, to add an element to a list, you can use the add method as follows:
llist.add(3);

The following program shows the initializations of the list using the add method. It also
uses the double brace initialization technique.
import java.util.*;

public class Main {


public static void main(String args[]) {
// ArrayList.add method
List<String> str_list = new ArrayList<String>();
str_list.add("Java");
str_list.add("C++");
System.out.println("ArrayList : " + str_list.toString());

// LinkedList.add method
List<Integer> even_list = new LinkedList<Integer>();
even_list.add(2);
even_list.add(4);
System.out.println("LinkedList : " + even_list.toString());

// double brace initialization - use add with declaration & initialization


List<Integer> num_stack = new Stack<Integer>(){{ add(10);add(20); }};
System.out.println("Stack : " + num_stack.toString());
}
}
Output:

This program has three different list declarations i.e. ArrayList, LinkedList, and Stack.

ArrayList and LinkedList objects are instantiated and then the add methods are called to
add elements to these objects. For stack, double brace initialization is used in which the add
method is called during the instantiation itself.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

List interface & its methods


The following table shows various functions provided by the list interface in Java.
List
Method Prototype Description
method

size int size () Returns the size of the list i.e. number of
elements in the List or the length of the list.

clear void clear () Clears the list by removing all the elements in
the list

add void add (int index, Adds the given element to the list at the given
Object element) index

boolean add (Object Adds the given element at the end of the list
o)

addAll boolean addAll Appends the entire given collection to the end
(Collection c) of the list

boolean addAll (int Inserts the given collection(all elements) to the


index, Collection c) list at the specified index

contains boolean contains Checks if the specified element is present in the


(Object o) list and returns true if present

containsAll boolean containsAll Checks if the specified collection (all elements)


(Collection c) is part of the list. Returns true of yes.

equals boolean equals Compares the specified object for equality with
(Object o) elements of the list

Get Object get (int index) Returns the element in the list specified by
index

hashCode int hashCode () Returns the hash code value of the List.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

List
Method Prototype Description
method

indexOf` int indexOf (Object o) Finds the first occurrence of the input element
and returns its index

isEmpty boolean isEmpty () Checks if the list is empty

lastIndexOf int lastIndexOf Finds the last occurrence of the input element
(Object o) in the list and returns its index

remove Object remove (int Removes the element at the specified index
index)

boolean remove Removes the element at its first occurrence in


(Object o) the list

removeAll boolean removeAll Removes all elements contained in the


(Collection c) specified collection from the list

retainAll boolean retainAll Opposite of removeAll. Retains the element


(Collection c) specified in the input collection in the list.

Set Object set (int index, Changes the element at the specified index by
Object element) setting it to the specified value

subList List subList (int Returns sublist of elements between


fromIndex, int fromIndex(inclusive), and toIndex(exclusive).
toIndex)

sort void sort Sorts the list element as per the specified
(Comparator c) comparator to give an ordered list

toArray Object[] toArray () Returns array representation of the list

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

List
Method Prototype Description
method

Object [] toArray Returns the array representation whose


(Object [] a) runtime type is the same as a specified array
argument

iterator Iterator iterator () Returns an Iterator for the list

listIterator ListIterator Returns a ListIterator for the list


listIterator ()

ListIterator Returns a ListIterator starting at the specified


listIterator (int index) index in the list

Set
Set in Java is an interface that is a part of the Java Collection Framework and implements
the Collection interface. A set collection provides the features of a mathematical set.

A set can be defined as a collection of unordered objects and it cannot contain duplicate
values. As the set interface inherits the Collection interface, it implements all the methods
of the Collection interface.

The set interface is implemented by classes and interfaces as shown in the below
diagram.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

As shown in the above diagram, Set interface is inherited by classes, HashSet, TreeSet,
LinkedHashSet, and EnumSet. The interfaces SortedSet and NavigableSet also implement
Set interface.

Some of the important characteristics of the Set interface are given below:
1. The set interface is a part of the Java Collections Framework.
2. The set interface allows for unique values.
3. It can have at most one null value.
4. Java 8 provides a default method for the set interface – Spliterator.
5. The set interface does not support the indexes of the elements.
6. The set interface supports generics.

How To Create A Set?

The set interface in Java is a part of the java.util package. To include a set interface in the
program, we have to use one of the following import statements.

import java.util.*;
or

import java.util.Set;
Once set interface functionality is included in the program, we can create a set in Java using
any of the set classes (classes that implement set interface) as shown below.

Set<String> colors_Set = new HashSet<>();


We can then initialize this set object by adding a few elements to it using the add method.

colors_Set.add(“Red”);
colors_Set.add(“Green”);
colors_Set.add(“Blue”);

Set Example In Java

Let’s implement a simple example in Java to demonstrate the Set interface.


import java.util.*;
public class Main {
public static void main(String[] args) {
// Set demo with HashSet
Set<String> Colors_Set = new HashSet<String>();

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Colors_Set.add("Red");
Colors_Set.add("Green");
Colors_Set.add("Blue");
Colors_Set.add("Cyan");
Colors_Set.add("Magenta");
//print set contents
System.out.print("Set contents:");
System.out.println(Colors_Set);

// Set demo with TreeSet


System.out.print("\nSorted Set after converting to TreeSet:");
Set<String> tree_Set = new TreeSet<String>(Colors_Set);
System.out.println(tree_Set);
}
}
Output:
Set contents:[Red, Cyan, Blue, Magenta, Green]
Sorted Set after converting to TreeSet:[Blue, Cyan, Green, Magenta, Red]

Set interface & its methods:


Set Methods API
Given below are the methods supported by the Set interface. These methods perform basic
operations like add, remove, contains, etc. along with the other operations.

Method Method Prototype Description

add boolean add ( E e ) Adds the element e to the set if it is not


present in the set

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Method Method Prototype Description

addAll boolean addAll (Collection c ) Adds the element of the collection c to the
set.

remove boolean remove(Object o ) Deletes the given element o from the set.

removeAll boolean removeAll ( Collection Removes the elements present in the given
c) collection c from the set.

contains boolean contains ( Object o ) Checks if the given element o is present in


the set. Returns true if yes.

containsAll boolean containsAll ( Checks if the set contains all the elements
Collection c ) in the specified collection; Returns true if
yes.

isEmpty boolean isEmpty () Checks if the set is empty

retainAll boolean retainAll (Collection c) Set retains all the elements in the given
collection c

clear void clear () Clears the set by deleting all the elements
from the set

iterator Iterator iterator () Used to obtain the iterator for the set

toArray Object[] toArray () Converts the set to array representation


that contains all the elements in the set.

size int size () Returns the total number of elements or


size of the set.

hashCode hashCode () Returns hashCode of the set.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Example:
import java.util.*;
public class Main {
public static void main(String args[]) {
//declare a set class (HashSet)
Set<Integer> numSet = new HashSet<Integer>();
//add an element => add
numSet.add(13);
//add a list to the set using addAll method
numSet.addAll(Arrays.asList(new Integer[] {1,6,4,7,3,9,8,2,12,11,20}));
//print the set
System.out.println("Original Set (numSet):" + numSet);
//size()
System.out.println("\nnumSet Size:" + numSet.size());
//create a new set class and initialize it with list elements
Set<Integer> oddSet = new HashSet<Integer>();
oddSet.addAll(Arrays.asList(new Integer[] {1, 3, 7, 5, 9}));
//print the set
System.out.println("\nOddSet contents:" + oddSet);
//contains ()
System.out.println("\nnumSet contains element 2:" + numSet.contains(3));
//containsAll ()
System.out.println("\nnumSet contains collection oddset:" +
numSet.containsAll(oddSet));
// retainAll () => intersection
Set<Integer> set_intersection = new HashSet<Integer>(numSet);
set_intersection.retainAll(oddSet);
System.out.print("\nIntersection of the numSet & oddSet:");
System.out.println(set_intersection);
// removeAll () => difference
Set<Integer> set_difference = new HashSet<Integer>(numSet);
set_difference.removeAll(oddSet);
System.out.print("Difference of the numSet & oddSet:");
System.out.println(set_difference);

// addAll () => union


Set<Integer> set_union = new HashSet<Integer>(numSet);
set_union.addAll(oddSet);
System.out.print("Union of the numSet & oddSet:");
System.out.println(set_union);
}
}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Map
Maps collection in Java is a collection that maps a key to a value. It is a collection consisting
of keys and values. Each entry in the map consists of a key with its corresponding value.
The keys are unique in maps. Maps can be used typically when we need to modify a
collection based on a key value.

Maps In Java
The map in Java is a part of the java.util.map interface. The map interface is not a part of the
collection interface and that is the reason for which maps are different from the other
collections.

The general hierarchy of the map interface is shown below.

As shown above there are two interfaces to implement map i.e. map interface and
sortedMap interface. There are three classes namely i.e. HashMap, TreeMap, and
LinkedHashMap.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

These map types are described below:


Class Description

LinkedHashMap Extends from HashMap class. This map maintains the insertion order

HashMap Implement a map interface. No order is maintained by HashMap.

TreeMap Implements both map and sortedMap interface. TreeMap maintains an


ascending order.

Points To Remember About Maps.


1. In maps, each key can map to the at most one value. Also, there cannot be
duplicate keys in maps.
2. Map implementations like HashMap and LinkedHashMap allow null key and
null values. However, TreeMap does not allow it.
3. A map cannot be traversed as it is. Hence for traversing, it needs to be
converted to set using keyset () or entrySet () method.

Create A Map In Java


To create a map in Java, first, we have to include the interface in our program. We can use
one of the following statements in the program to import the map functionality.

import java.util.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;

We need to instantiate a concrete implementation of the map as it is an interface.

The following statements create a map in Java.


Map hash_map = new HashMap();
Map tree_map = new TreeMap();
The above statements will create maps with default specifications.
We can also create generic maps specifying the types for both key and value.

Map<String, Object> myMap = new HashMap<String, Object>();


The above definition will have keys of type string and objects as values.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Map interface & its classes


Map interface in Java supports various operations similar to those supported by other
collections. In this section, we will discuss the various methods provided by Map API in
Java. As the scope of this tutorial is limited to introducing a map interface in general, we
will not describe these methods.

We will discuss these methods in detail while discussing map interface classes.

The following table lists all the methods provided by map API.
Method
Method Prototype Description
Name

get V get(Object key) Returns the object or value for the given key

put V put(Object key, Object Insert key-value entry in the map


value)

putAll void putAll(Map map) Insert given map entries in the map. In other
words copies or clones a map.

keySet Set keySet() Returns set view of the map.

entrySet Set< Map.Entry< K,V >> Returns set the view for a given map
entrySet()

values Collection values() Returns collection view of the values in the


map.

remove V remove(Object key) Delete a map entry for the given key

size int size() Returns number of entries in the map

clear void clear() Clears the map

isEmpty boolean isEmpty() Checks if the map is empty and returns true if
yes.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Method
Method Prototype Description
Name

containsValue boolean Returns true if the map contains the value


containsValue(Object equal to the given value
value)

containsKey boolean Returns true if a given key exists in the map


containsKey(Object key)

equals boolean equals(Object o) Compares specified object o with the map

hashCode int hashCode() returns the hash code for the Map

forEach void forEach(BiConsumer< Performs given action for each entry in the
? super K,? super V > map
action)

getOrDefault V getOrDefault(Object key, Returns specified value for the given key or
V defaultValue) its default value if the key is not present

replace V replace(K key, V value) Replaces the given key with the specified
value

All the above methods are supported by the map interface. Note that the methods that
appear shaded are the new methods that were included in Java 8.

Java Map Implementation


The following program implements a map example in Java. Here we use most of the
methods discussed above.

The example demonstrates various get operations, put, and set operations.
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

public class Main {


public static void main(String[] args) {
//create a map
Map<String, String> country_map = new HashMap<>();
//assign values to the map
country_map.put("IND", "India");
country_map.put("SL", "Srilanka");
country_map.put("CHN", "China");
country_map.put("KOR", "Korea");
country_map.put(null, "Z"); // null key
country_map.put("XX", null); // null value

String value = country_map.get("CHN"); // get


System.out.println("Key = CHN, Value : " + value);

value = country_map.getOrDefault("XX", "Default Value"); //getOrDefault


System.out.println("\nKey = XX, Value : " + value);

boolean keyExists = country_map.containsKey(null); //containsKey


boolean valueExists = country_map.containsValue("Z"); //containsValue

System.out.println("\nnull keyExists : " + keyExists + ", null valueExists= " + valueExists);

Set<Entry<String, String>> entrySet = country_map.entrySet(); //entrySet


System.out.println("\nentry set for the country_map: " + entrySet);

System.out.println("\nSize of country_map : " + country_map.size()); //size

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Map<String, String> data_map = new HashMap<>();


data_map.putAll(country_map); //putAll
System.out.println("\ndata_map mapped to country_map : " + data_map);

String nullKeyValue = data_map.remove(null); //remove


System.out.println("\nnull key value for data_map : " + nullKeyValue);
System.out.println("\ndata_map after removing null key = " + data_map);

Set<String> keySet = country_map.keySet(); //keySet


System.out.println("\ndata map keys : " + keySet);

Collection<String> values = country_map.values(); //values


System.out.println("\ndata map values : " + values);

country_map.clear(); //clear
System.out.println("\ndata map after clear operation, is empty :" +
country_map.isEmpty());
}
}
Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

CHAPTER-2
Introduction to JFC and Swing
****************************************************************
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-
based applications. 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.

The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.

What Is Java Swing

Java provides many GUI frameworks that help us in developing a variety of GUI
applications. We have seen one in our previous tutorial i.e. Abstract Window Toolkit or
AWT. AWT is one of the oldest GUI frameworks in Java and is also platform dependent.
Another disadvantage of AWT is its heavyweight components.

In this tutorial, we will discuss yet another GUI framework in Java i.e. “SWING”. The Swing
framework in Java is a part of Java Foundation Classes or commonly called JFCs. JFC is an
API that is similar to MFCs (Microsoft Foundation Classes) in C++. JFC contains Swing, AWT,
and Java2D.

The Swing framework in Java is built on top of the AWT framework and can be used to
create GUI applications just like AWT. But unlike AWT, the Swing components are light-
weight and are platform-independent.

The Swing framework is written entirely in Java. The Swing framework in Java is provided
through the ‘javax.swing’ package. The classes in the javax.swing package begins with the
letter ‘J’. So in a javax.swing package, we will have classes like JButton, JFrame, JTextField,
JTextArea, etc.

In general, the Swing API has every control defined in javax.swing package that is present
in AWT. So swing in a way acts as a replacement of AWT. Also, Swing has various advanced
component tabbed panes. Swing API in Java adapts MVC (Model View Controller)
Architecture.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Many programmers think that JFC and Swing is one and the same thing, but that is not so.
JFC contains Swing [A UI component package] and quite a number of other items:
• Cut and paste: Clipboard support
• Accessibility features: Aimed at developing GUI’s for users with disabilities
• The Desktop Colors Features Has been Firstly introduced in Java 1.1
• The Java 2D: it has Improved colors, images, and also texts support

Features Of Swing Class


1. Swing components are platform-independent.
2. The API is extensible.
3. Swing components are light-weight. The swing components are written in
pure Java and also components are rendered using Java code instead of
underlying system calls.
4. Swing API provides a set of advanced controls like TabbedPane, Tree,
Colorpicker, table controls, etc. which are rich in functionality.
5. The swing controls are highly customizable. This is because the appearance
or look-and-feel of the component is independent of internal representation
and hence we can customize it in the way we desire.
6. We can simply change the values and thus alter the look-and-feel at runtime.

Features of the Java Foundation Classes


The Java Foundation Classes are a set of GUI components and services which simplify the
development and deployment of commercial-quality desktop and Internet/Intranet
applications.

- Java Foundation classes are core to the Java 2 Platform.


- All JFC components are JavaBeans components and therefore reusable, interoperable, and
portable.
- JFC offers an open architecture. Third-party JavaBeans components can be used to
enhance applications written using JFC.
- Truly cross-platform.
- Fully customizable.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Swing API Components

Swing has a big set of components that we can include in our programs and avail the rich
functionalities using which we can develop highly customized and efficient GUI
applications.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

So what is a component?
A component can be defined as a control that can be represented visually and is usually
independent. It has got a specific functionality and is represented as an individual class in
Swing API.

For example, class JButton in swing API is a button component and provides the
functionality of a button.
One or more components form a group and this group can be placed in a “Container”. A
container provides a space in which we can display components and also manage their
spacing, layout, etc.

JComponent Class

The JComponent class is the base class of all Swing components except top-level containers.
Swing components whose names begin with "J" are descendants of the JComponent class.
For example, JButton, JScrollPane, JPanel, JTable etc. But, JFrame and JDialog don't inherit
JComponent class because they are the child of top-level containers.

The JComponent class extends the Container class which itself extends Component. The
Container class has support for adding components to the container.

Constructor

Constructor Description

JComponent() Default JComponent constructor.

Useful Methods

Modifier and Method Description


Type

void setBackground(Color bg) It sets the background color of this


component.

void setFont(Font font) It sets the font for this component.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

void setMaximumSize(Dimension It sets the maximum size of this


maximumSize) component to a constant value.

void setMinimumSize(Dimension It sets the minimum size of this


minimumSize) component to a constant value.

protected void setUI(ComponentUI newUI) It sets the look and feel delegate for
this component.

void setVisible(boolean aFlag) It makes the component visible or


invisible.

void setForeground(Color fg) It sets the foreground color of this


component.

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.

Java JComponent Example

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

class MyJComponent extends JComponent {


public void paint(Graphics g) {
g.setColor(Color.green);
g.fillRect(30, 30, 100, 100);
}
}
public class JComponentExample {
public static void main(String[] arguments) {
MyJComponent com = new MyJComponent();
// create a basic JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComponent Example");
frame.setSize(300,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the JComponent to main frame
frame.add(com);
frame.setVisible(true);
}
}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Windows
Java JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.

Java Swing Examples

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

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

}
}

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();

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

}
}

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.

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();
}}

Dialog Boxes and Panels


Java JDialog

The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless dialog without a title and


without a specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with specified Frame


as its owner and an empty title.

JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.

Java JDialog Example

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}

Output:C++ vs Java

Panel

The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class.

It doesn't have title bar.

Commonly used Constructors:

Constructor Description

JPanel() It is used to create a new JPanel with a double buffer and a


flow layout.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JPanel(boolean It is used to create a new JPanel with FlowLayout and the


isDoubleBuffered) specified buffering strategy.

JPanel(LayoutManager It is used to create a new JPanel with the specified layout


layout) manager.

Java JPanel Example


import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Output:

Labels
Java 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.

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty string for
the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and
int horizontal alignment.
horizontalAlignment)

Commonly used Methods:

Methods Description

String getText() t returns the text string that a label displays.

void setText(String text) It defines the single line of text this component will
display.

void setHorizontalAlignment(int It sets the alignment of the label's contents along


alignment) the X axis.

Icon getIcon() It returns the graphic image that the label displays.

int getHorizontalAlignment() It returns the alignment of the label's contents along


the X axis.

Java JLabel 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);

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

f.setVisible(true);
}
}

Output:

Buttons
Java 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.

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

JButton(Icon i) It creates a button with the specified icon object.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Commonly used Methods of AbstractButton class:

Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

Java JButton 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);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Check Boxes
Java 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.

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box button with no


text, no icon.

JChechBox(String s) Creates an initially unselected check box with text.

JCheckBox(String text, boolean Creates a check box with text and specifies whether or not
selected) it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken from the
Action supplied.

Commonly used Methods:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Methods Description

AccessibleContext It is used to get the AccessibleContext associated with


getAccessibleContext() this JCheckBox.

protected String paramString() It returns a string representation of this JCheckBox.

Java JCheckBox 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:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Menus
Java JMenuBar, JMenu and JMenuItem

The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.

The object of JMenu class is a pull down menu component which is displayed from the menu
bar. It inherits the JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.

Java JMenuItem and JMenu Example


import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

submenu=new JMenu("Sub Menu");


i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}}

Output:Play Vide

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Toolbars
JToolBar container allows us to group other components, usually buttons with icons in a
row or column. JToolBar provides a component which is useful for displaying commonly
used actions or controls.

Constructors

Constructor Description

JToolBar() It creates a new tool bar; orientation defaults to


HORIZONTAL.

JToolBar(int orientation) It creates a new tool bar with the specified orientation.

JToolBar(String name) It creates a new tool bar with the specified name.

JToolBar(String name, int It creates a new tool bar with a specified name and
orientation) orientation.

Useful Methods

Modifier and Type Method Description

JButton add(Action a) It adds a new JButton which


dispatches the action.

protected void addImpl(Component comp, Object If a JButton is being added, it


constraints, int index) is initially set to be disabled.

void addSeparator() It appends a separator of


default size to the end of the
tool bar.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

protected createActionChangeListener(JButton It returns a properly


PropertyChangeListener b) configured
PropertyChangeListener
which updates the control
as changes to the Action
occur, or null if the default
property change listener for
the control is desired.

protected JButton createActionComponent(Action a) Factory method which


creates the JButton for
Actions added to the
JToolBar.

ToolBarUI getUI() It returns the tool bar's


current UI.

void setUI(ToolBarUI ui) It sets the L&F object that


renders this component.

void setOrientation(int o) It sets the orientation of the


tool bar.

Java JToolBar Example


import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;

public class JToolBarExample {


public static void main(final String args[]) {
JFrame myframe = new JFrame("JToolBar Example");

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JToolBar toolbar = new JToolBar();
toolbar.setRollover(true);
JButton button = new JButton("File");
toolbar.add(button);
toolbar.addSeparator();
toolbar.add(new JButton("Edit"));
toolbar.add(new JComboBox(new String[] { "Opt-1", "Opt-2", "Opt-3", "Opt-4" }));
Container contentPane = myframe.getContentPane();
contentPane.add(toolbar, BorderLayout.NORTH);
JTextArea textArea = new JTextArea();
JScrollPane mypane = new JScrollPane(textArea);
contentPane.add(mypane, BorderLayout.EAST);
myframe.setSize(450, 250);
myframe.setVisible(true);
}
}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Implementing Action interface

The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in java.awt.event package

. It has only one method: actionPerformed().

actionPerformed() method

The actionPerformed() method is invoked automatically whenever you click on the


registered component.

public abstract void actionPerformed(ActionEvent e);

How to write ActionListener

The common approach is to implement the ActionListener. If you implement the


ActionListener class, you need to follow 3 steps:

1) Implement the ActionListener interface in the class:

public class ActionListenerExample Implements ActionListener

2) Register the component with the Listener:

component.addActionListener(instanceOfListenerclass);

3) Override the actionPerformed() method:

public void actionPerformed(ActionEvent e)


{

//Write the code here


}

Java ActionListener Example: On Button click


import java.awt.*;
import java.awt.event.*;
//1st step
public class ActionListenerExample implements ActionListener{

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

public static void main(String[] args) {


Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
//2nd step
b.addActionListener(this);
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
//3rd step
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
}

Output:

Java ActionListener Example: Using Anonymous class

We can also use the anonymous class to implement the ActionListener. It is the shorthand
way, so you do not need to follow the 3 steps:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

b.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){


tf.setText("Welcome to Javatpoint.");
}
});

Let us see the full code of ActionListener using anonymous class.

import java.awt.*;
import java.awt.event.*;
public class ActionListenerExample {
public static void main(String[] args) {
Frame f=new Frame("ActionListener Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Pane
What is pane in Swing Java?

A layered pane is a Swing container that provides a third dimension for positioning
components: depth, also known as Z order. When adding a component to a layered pane,
you specify its depth as an integer. The higher the number, closer the component is to the "top"
position within the container.

JScrollPane

Java JScrollPane

A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.

Constructors

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Constructor Purpose

JScrollPane() It creates a scroll pane. The Component parameter, when


present, sets the scroll pane's client. The two int parameters,
JScrollPane(Component) when present, set the vertical and horizontal scroll bar policies
(respectively).

JScrollPane(int, int)

JScrollPane(Component,
int, int)

Useful Methods

Modifier Method Description

void setColumnHeaderView(Component) It sets the column header for the scroll


pane.

void setRowHeaderView(Component) It sets the row header for the scroll pane.

void setCorner(String, Component) It sets or gets the specified corner. The


int parameter specifies which corner and
Component getCorner(String) must be one of the following constants
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JScrollPane Example
// Java Program to illustrate the
// ScrollPaneLayout class
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;

// create a class Geeks extending JFrame


public class Geeks extends JFrame

// Declaration of objects of the


// JScrollPane class.
JScrollPane scrollpane;

// Constructor of Geeks class


public Geeks()
{

// used to call super class


// variables and methods
super("JScrollPane Demonstration");

// Function to set size of JFrame.


setSize(300, 200);

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

// Function to set Default close


// operation of JFrame.
setDefaultCloseOperation(EXIT_ON_CLOSE);

// to contain a string value


String categories[] = {"Geeks", "Language", "Java",
"Sudo Placement", "Python",
"CS Subject", "Operating System",
"Data Structure", "Algorithm",
"PHP language", "JAVASCRIPT",
"C Sharp" };

// Creating Object of "JList" class


JList list = new JList(categories);

// Creating Object of
// "scrollpane" class
scrollpane = new JScrollPane(list);

// to get content pane


getContentPane().add(scrollpane, BorderLayout.CENTER);
}

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

// Creating Object of Geeks class.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Geeks sl = new Geeks();

// Function to set visibility of JFrame.


sl.setVisible(true);
}
}
Desktop pane
The JDesktopPane class, can be used to create "multi-document" applications. A multi-
document application can have many windows included in it. We do it by making the
contentPane in the main window as an instance of the JDesktopPane class or a subclass.
Internal windows add instances of JInternalFrame to the JdesktopPane instance. The
internal windows are the instances of JInternalFrame or its subclasses.

Constructor

Constructor Description

JDesktopPane() Creates a new JDesktopPane.

Java JDesktopPane Example


import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
public class JDPaneDemo extends JFrame
{
public JDPaneDemo()
{
CustomDesktopPane desktopPane = new CustomDesktopPane();
Container contentPane = getContentPane();
contentPane.add(desktopPane, BorderLayout.CENTER);
desktopPane.display(desktopPane);

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

setTitle("JDesktopPane Example");
setSize(300,350);
setVisible(true);
}
public static void main(String args[])
{
new JDPaneDemo();
}
}
class CustomDesktopPane extends JDesktopPane
{
int numFrames = 3, x = 30, y = 30;
public void display(CustomDesktopPane dp)
{
for(int i = 0; i < numFrames ; ++i )
{
JInternalFrame jframe = new JInternalFrame("Internal Frame " + i , true, true, true,
true);

jframe.setBounds(x, y, 250, 85);


Container c1 = jframe.getContentPane( ) ;
c1.add(new JLabel("I love my country"));
dp.add( jframe );
jframe.setVisible(true);
y += 85;
}
}
}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Scrollbars
Java JScrollBar

The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.

Commonly used Constructors:

Constructor Description

JScrollBar() Creates a vertical scrollbar with the initial values.

JScrollBar(int orientation) Creates a scrollbar with the specified orientation and


the initial values.

JScrollBar(int orientation, int value, int Creates a scrollbar with the specified orientation,
extent, int min, int max) value, extent, minimum, and maximum.

Java JScrollBar Example


import javax.swing.*;
class ScrollBarExample
{
ScrollBarExample(){

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JFrame f= new JFrame("Scrollbar Example");


JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollBarExample();
}}

Output:

Lists and Combo Boxes


Java 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.

Commonly used Constructors:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified
array.

JList(ListModel<ary> Creates a JList that displays elements from the specified, non-
dataModel) null, model.

Commonly used Methods:

Methods Description

Void It is used to add a listener to the list, to be


addListSelectionListener(ListSelectionListener notified each time a change to the
listener) selection occurs.

int getSelectedIndex() It is used to return the smallest selected


cell index.

ListModel getModel() It is used to return the data model that


holds a list of items displayed by the JList
component.

void setListData(Object[] listData) It is used to create a read-only ListModel


from an array of objects.

Java JList Example


import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
String l1={“item1”,”item2”,”item3”,”item4”};
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

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

Output:

Java JComboBox

The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.

Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified arr

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Ve

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

void setEditable(boolean b) It is used to determine whether the JComboBox is


editable.

void addActionListener(ActionListener It is used to add the ActionListener.


a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox 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);

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

Output:

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

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the specified text.

JTextField(String text, int Creates a new TextField initialized with the specified text
columns) and columns.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JTextField(int columns) Creates a new empty TextField with the specified number of
columns.

Commonly used Methods:

Methods Description

void addActionListener(ActionListener It is used to add the specified action listener to


l) receive action events from this textfield.

Action getAction() It returns the currently set Action for this


ActionEvent source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so


removeActionListener(ActionListener l) that it no longer receives action events from this
textfield.

Java JTextField 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);
f.setVisible(true);
}

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Output:

Java 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

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, int Creates a text area with the specified number of rows and
column) columns that displays no text initially.

JTextArea(String s, int row, int Creates a text area with the specified number of rows and
column) columns that displays specified text.

Commonly used Methods:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

void insert(String s, int It is used to insert the specified text on the specified
position) position.

void append(String s) It is used to append the given text to the end of the
document.

Java JTextArea 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[])
{
new TextAreaExample();
}}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Java 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.

Commonly used Constructors:

Constructor Description

JPasswordField() Constructs a new JPasswordField, with a default document,


null starting text string, and 0 column width.

JPasswordField(int columns) Constructs a new empty JPasswordField with the specified


number of columns.

JPasswordField(String text) Constructs a new JPasswordField initialized with the specified


text.

JPasswordField(String text, int Construct a new JPasswordField initialized with the specified
columns) text and columns.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Java JPasswordField 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:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Colors and File Choosers


Java JColorChooser

The JColorChooser class is used to create a color chooser dialog box so that user can select
any color. It inherits JComponent class.

Commonly used Constructors:

Constructor Description

JColorChooser() It is used to create a color chooser panel with white color


initially.

JColorChooser(color It is used to create a color chooser panel with the specified


initialcolor) color initially.

Commonly used Methods:

Method Description

void addChooserPanel(AbstractColorChooserPanel It is used to add a color chooser


panel) panel to the color chooser.

static Color showDialog(Component c, String title, Color It is used to show the color chooser
initialColor) dialog box.

ava JColorChooser Example with ActionListener


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserExample extends JFrame implements ActionListener{

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JFrame f;
JButton b;
JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
b=new JButton("Pad Color");
b.setBounds(200,250,100,30);
ta=new JTextArea();
ta.setBounds(10,10,300,200);
b.addActionListener(this);
f.add(b);f.add(ta);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
ta.setBackground(c);
}
public static void main(String[] args) {
new ColorChooserExample();
}
}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Java JFileChooser

The object of JFileChooser class represents a dialog window from which the user can select
file. It inherits JComponent class.

Commonly used Constructors:

Constructor Description

JFileChooser() Constructs a JFileChooser pointing to the user's


default directory.

JFileChooser(File currentDirectory) Constructs a JFileChooser using the given File as the


path.

JFileChooser(String Constructs a JFileChooser using the given path.


currentDirectoryPath)

1. JFileChooser() – empty constructor that points to user’s default directory

• Java

// Using this process to invoke the constructor,


// JFileChooser points to user's default directory
JFileChooser j = new JFileChooser();

// Open the save dialog


j.showSaveDialog(null);

Output of the code snippet:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

2. JFileChooser(String) – uses the given path

• Java

// Using this process to invoke the constructor,


// JFileChooser points to the mentioned path
JFileChooser j = new JFileChooser("d:");

// Open the save dialog


j.showSaveDialog(null);

Output of the code snippet:

3. JFileChooser(File) – uses the given File as the path

• Java

// Using this process to invoke the constructor,


// JFileChooser points to the mentioned path
// of the file passed
JFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New folder\\"));

// Open the save dialog


j.showSaveDialog(null);

Output of the code snippet:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Tables and Trees

Java JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

Commonly used Constructors:

Constructor Description

JTable() Creates a table with empty cells.

JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable Example


import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}

Output:

Java JTree

The JTree class is used to display the tree structured data or hierarchical data. JTree is a
complex component. It has a 'root node' at the top most which is a parent for all nodes in the
tree. It inherits JComponent class.

Commonly used Constructors:

Constructor Description

JTree() Creates a JTree with a sample model.

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

JTree(Object[] Creates a JTree with every element of the specified array as the child of a
value) new root node.

JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which displays the
root) root node.

Java JTree Example


import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}

Output:

Ms. Shraddha Sonawane D. G. Ruparel College


UNIT-2 SYCS-JAVA

Ms. Shraddha Sonawane D. G. Ruparel College


Event Handling:
What is an Event?
Change in the state of an object is known as event i.e. event describes
the change in state of source. Events are generated as result of user
interaction with the graphical user interface components. For example,
clicking on a button, moving the mouse, entering a character through
keyboard,selecting an item from list, scrolling the page are the activities
that causes an event to happen.

Types of Event
The events can be broadly classified into two categories:
 Foreground Events - Those events which require the direct interaction of
user.They are generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example, clicking on a
button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page etc.
 Background Events - Those events that require the interaction of end user
are known as background events. Operating system interrupts, hardware or
software failure, timer expires, an operation completion are the example of
background events.

What is 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.Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is
responsible for providing information of the occurred event to it's handler.
Java provide as with classes for source object.
 Listener - It is also known as event handler.Listener is responsible for
generating response to an event. From java implementation point of view
the listener is also an object. Listener waits until it receives an event. Once
the event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely
separated from the logic that generates the event. The user interface
element is able to delegate the processing of an event to the separate
piece of code. In this model ,Listener needs to be registered with the
source object so that the listener can receive the event notification. This
is an efficient way of handling the event because the event notifications
are sent only to those listener that want to receive them.
Steps involved in event handling
 The User clicks the button and the event is generated.
 Now the object of concerned event class is created automatically and
information about the source and the event get populated with in same
object.
 Event object is forwarded to the method of registered listener class.
 the method is now get executed and returns.

Points to remember about listener


 In order to design a listener class we have to develop some listener
interfaces.These Listener interfaces forecast some public abstract callback
methods which must be implemented by the listener class.
 If you do not implement the any if the predefined interfaces then your class
can not act as a listener class for a source object.

Callback Methods
These are the methods that are provided by API provider and are defined
by the application programmer and invoked by the application developer.
Here the callback methods represents an event method. In response to
an event java jre will fire callback method. All such callback methods are
provided in listener interfaces.
If a component wants some listener will listen to it's events the the
source must register itself to the listener.

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many
event classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener
AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:
1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
 Button
 public void addActionListener(ActionListener a){}
 MenuItem
 public void addActionListener(ActionListener a){}
 TextField
 public void addActionListener(ActionListener a){}
 public void addTextListener(TextListener a){}
 TextArea
 public void addTextListener(TextListener a){}
 Checkbox
 public void addItemListener(ItemListener a){}
 Choice
 public void addItemListener(ItemListener a){}
 List
 public void addActionListener(ActionListener a){}
 public void addItemListener(ItemListener a){}
Java Event Handling Code
We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
{
TextField tf;
AEvent()
{

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
public static void main(String args[])
{
new AEvent();
}
}
public void setBounds(intxaxis, intyaxis, int width, int height); have
been used in the above example that sets the position of the component it
may be button, textfield etc.

2) Java event handling by outer class


import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame
{
TextField tf;
AEvent2()
{
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener
{
AEvent2 obj;
Outer(AEvent2 obj)
{
this.obj=obj;
}
public void actionPerformed(ActionEvent e)
{
obj.tf.setText("welcome");
}
}

3) Java event handling by anonymous class


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame
{
TextField tf;
AEvent3()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener()
{
public void actionPerformed()
{
tf.setText("hello");
}
});

add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
new AEvent3();
}
}

AWT Event Adapters


Adapters are abstract classes for receiving various events. The methods
in these classes are empty. These classes exists as convenience for
creating listener objects.

AWT Adapters:
Following is the list of commonly used adapters while listening GUI
events in AWT.

Sr. No. Adapter & Description

1 FocusAdapter
An abstract adapter class for receiving focus events.

2 KeyAdapter
An abstract adapter class for receiving key events.

3 MouseAdapter
An abstract adapter class for receiving mouse events.

4 MouseMotionAdapter
An abstract adapter class for receiving mouse motion events.

5 WindowAdapter
An abstract adapter class for receiving window events.

The class FocusAdapter is an abstract (adapter) class for receiving


keyboard focus events. All methods of this class are empty. This class is
convenience class for creating listener objects.
UNIT 1

Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database.

We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

JDBC is an standard API specification developed in order to move data from frontend to
backend. This API consists of classes and interfaces written in Java. It basically acts as an
interface (not the one we use in Java) or channel between your Java program and databases i.e
it establishes a link between the two so that a programmer could send data from Java code and
store it in the database for future use.

The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of
JDBC API are given below:

 Driver interface
 Connection interface
 Statement interface
 PreparedStatement interface
 CallableStatement interface
 ResultSet interface
 ResultSetMetaData interface
 DatabaseMetaData interface
 RowSet interface

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

A list of popular classes of JDBC API are given below:

 DriverManager class
 Blob class
 Clob class
 Types class

Why Should We Use JDBC


Before 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 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:

 Connect to the database


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

What is API
API (Application programming interface) is a document that contains a description of all the
features of a product or software. It represents classes and interfaces that software programs
can follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc.

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.

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

The JDBC API uses a driver manager and database-specific drivers to provide transparent
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.

Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

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, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

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.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC

bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged
because of thin driver.

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC

method calls into native calls of the database API. It is not written entirely in java.

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

Advantage:

performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

The Native driver needs to be installed on the each client machine.

The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

Advantage:

No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.

Disadvantages:

Network support is required on client machine.

Requires database-specific coding to be done in the middle tier.

Maintenance of Network Protocol driver becomes costly because it requires database-specific


coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol.

That is why it is known as thin driver. It is fully written in Java language.

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

Advantage:

Better performance than all other drivers.

No software is required at client side or server side.

Disadvantage:

Drivers depend on the Database.

Which Driver to use When?


If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is type-4.

If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.

Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.

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:

1. Register the Driver class


2. Create connection
3. Create statement
4. Execute queries
5. 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 load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

Here, Java program is loading oracle driver to establish database connection.

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

2) Create the connection object

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

Syntax of getConnection() method

public static Connection getConnection(String url)throws SQLException

public static Connection getConnection(String url,String name,String password)

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

throws SQLException

Example to establish connection with the Oracle database

Connection con=DriverManager.getConnection(

"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 is 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 returns 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

Example to execute query

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

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2));

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

5) Close the connection object

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

Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();

Java Database Connectivity with MySQL


To connect Java application with the MySQL database, we need to follow 5 following steps.

In this example we are using MySql as the database. So we need to know following
informations for the mysql database:

Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

Connection URL: The connection URL for the mysql database


is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is
the server name on which mysql is running, we may also use IP address, 3306 is the port
number and sonoo is the database name. We may use any database, in such case, we need to
replace the sonoo with our database name.

Username: The default username for the mysql database is root.

Password: It is the password given by the user at the time of installing the mysql database. In
this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to create
database first.

create database demo;

use demo;

create table emp(id int(10),name varchar(40),age int(3));

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

Example to Connect Java Application with mysql database


In this example, sonoo is the database name, root is the username and password both.

import java.sql.*;

class MysqlCon{

public static void main(String args[]){

try{

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

Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/demo","root","root");

//here sonoo is database name, root is username and password

Statement stmt=con.createStatement();

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

while(rs.next())

System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}

1) Statement
Statement interface is used to execute normal SQL queries. You can’t pass the parameters to
SQL query at run time using this interface. This interface is preferred over other two interfaces
if you are executing a particular SQL query only once. The performance of this interface is also
very less compared to other two interfaces. In most of time, Statement interface is used for
DDL statements like CREATE, ALTER, DROP etc. For example,

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

//Creating The Statement Object

Statement stmt = con.createStatement();

//Executing The Statement

stmt.executeUpdate("CREATE TABLE STUDENT(ID NUMBER NOT NULL, NAME VARCHAR)");

2) PreparedStatement
PreparedStatement is used to execute dynamic or parameterized SQL queries.
PreparedStatement extends Statement interface. You can pass the parameters to SQL query at
run time using this interface. It is recommended to use PreparedStatement if you
are executing a particular SQL query multiple times. It gives better performance than Statement
interface. Because, PreparedStatement are precompiled and the query plan is created only
once irrespective of how many times you are executing that query. This will save lots of time.

//Creating PreparedStatement object

PreparedStatementpstmt = con.prepareStatement("update STUDENT set NAME = ? where ID


= ?");

//Setting values to place holders using setter methods of PreparedStatement object

pstmt.setString(1, "MyName"); //Assigns "MyName" to first place holder

pstmt.setInt(2, 111); //Assigns "111" to second place holder

//Executing PreparedStatement

pstmt.executeUpdate();

//Creating PreparedStatement object

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

PreparedStatementpstmt = con.prepareStatement("update STUDENT set NAME = ? where ID =


?");

//Setting values to place holders using setter methods of PreparedStatement object

pstmt.setString(1, "MyName"); //Assigns "MyName" to first place holder

pstmt.setInt(2, 111); //Assigns "111" to second place holder

//Executing PreparedStatement

pstmt.executeUpdate();

Example of Registration form in servlet


Here, you will learn that how to create simple registration form in servlet. We are using
oracle10g database. So you need to create a table first as given below:

CREATE TABLE "REGISTERUSER"

( "NAME" VARCHAR2(4000),

"PASS" VARCHAR2(4000),

"EMAIL" VARCHAR2(4000),

"COUNTRY" VARCHAR2(4000)

To create the registration page in servlet, we can separate the database logic from the servlet.
But here, we are mixing the database logic in the servlet only for simplicity of the program.

In this example, we have created the three pages.

 register.html
 Register.java
 web.xml

register.html

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

In this page, we have getting input from the user using text fields and combobox. The
information entered by the user is forwarded to Register servlet, which is responsible to store
the data into the database.

<html>

<body>

<form action="servlet/Register" method="post">

Name:<input type="text" name="userName"/><br/><br/>

Password:<input type="password" name="userPass"/><br/><br/>

Email Id:<input type="text" name="userEmail"/><br/><br/>

Country: <select name="userCountry">

<option>India</option>

<option>Pakistan</option>

<option>other</option>

</select>

<br/><br/>

<input type="submit" value="register"/>

</form>

</body>

</html>

Register.java

This servlet class receives all the data entered by user and stores it into the database. Here, we
are performing the database logic. But you may separate it, which will be better for the web
application.

import java.io.*;

import java.sql.*;

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

import javax.servlet.ServletException;

import javax.servlet.http.*;

public class Register extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

String p=request.getParameter("userPass");

String e=request.getParameter("userEmail");

String c=request.getParameter("userCountry");

try{

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

Connection con=DriverManager.getConnection(

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

PreparedStatement ps=con.prepareStatement(

"insert into registeruser values(?,?,?,?)");

ps.setString(1,n);

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

ps.setString(2,p);

ps.setString(3,e);

ps.setString(4,c);

int i=ps.executeUpdate();

if(i>0)

out.print("You are successfully registered...");

}catch (Exception e2) {System.out.println(e2);}

out.close();

web.xml file

The is the configuration file, providing information about the servlet.

<web-app>

<servlet>

<servlet-name>Register</servlet-name>

<servlet-class>Register</servlet-class>

</servlet>

Ms. Shraddha L. Sonawane D.G.Ruparel College


UNIT 1

<servlet-mapping>

<servlet-name>Register</servlet-name>

<url-pattern>/servlet/Register</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>register.html</welcome-file>

</welcome-file-list>

</web-app>

Ms. Shraddha L. Sonawane D.G.Ruparel College

You might also like