Sycs Java Unit-2
Sycs Java Unit-2
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).
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
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.
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:
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.
The following program shows the initializations of the list using the add method. It also
uses the double brace initialization technique.
import java.util.*;
// 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());
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.
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
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.
List
Method Prototype Description
method
indexOf` int indexOf (Object o) Finds the first occurrence of the input element
and returns its index
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)
Set Object set (int index, Changes the element at the specified index by
Object element) setting it to the specified value
sort void sort Sorts the list element as per the specified
(Comparator c) comparator to give an ordered list
List
Method Prototype Description
method
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.
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.
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.
colors_Set.add(“Red”);
colors_Set.add(“Green”);
colors_Set.add(“Blue”);
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);
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.
containsAll boolean containsAll ( Checks if the set contains all the elements
Collection c ) in the specified collection; Returns true if
yes.
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
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);
Output:
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.
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.
LinkedHashMap Extends from HashMap class. This map maintains the insertion order
import java.util.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
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
putAll void putAll(Map map) Insert given map entries in the map. In other
words copies or clones a map.
entrySet Set< Map.Entry< K,V >> Returns set the view for a given map
entrySet()
remove V remove(Object key) Delete a map entry for the given key
isEmpty boolean isEmpty() Checks if the map is empty and returns true if
yes.
Method
Method Prototype Description
Name
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.
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;
country_map.clear(); //clear
System.out.println("\ndata map after clear operation, is empty :" +
country_map.isEmpty());
}
}
Output:
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.
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.
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.
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
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.
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
Useful Methods
protected void setUI(ComponentUI newUI) It sets the look and feel delegate for
this component.
The methods of Component class are widely used in java swing that are given below.
Method Description
public void setLayout(LayoutManager m) sets the layout manager for the component.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
Output:
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.
We can write the code of swing inside the main(), constructor or any other method.
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
}
}
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
}
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets
the position of the button.
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);
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.
Constructor Description
JDialog(Frame owner, String title, It is used to create a dialog with the specified title, owner
boolean modal) Frame and modality.
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);
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.
Constructor Description
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.
Constructor Description
JLabel() Creates a JLabel instance with no image and with an empty string for
the title.
JLabel(String s, Icon i, Creates a JLabel instance with the specified text, image, and
int horizontal alignment.
horizontalAlignment)
Methods Description
void setText(String text) It defines the single line of text this component will
display.
Icon getIcon() It returns the graphic image that the label displays.
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.
Constructor Description
Methods Description
Output:
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.
Constructor Description
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.
Methods Description
Output:
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.
Output:Play Vide
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(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
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:
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
actionPerformed() method
component.addActionListener(instanceOfListenerclass);
Output:
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:
b.addActionListener(new ActionListener(){
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:
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
Constructor Purpose
JScrollPane(int, int)
JScrollPane(Component,
int, int)
Useful Methods
void setRowHeaderView(Component) It sets the row header for the scroll pane.
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;
// Creating Object of
// "scrollpane" class
scrollpane = new JScrollPane(list);
// Main Method
public static void main(String args[])
{
Constructor
Constructor Description
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);
Output:
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.
Constructor Description
JScrollBar(int orientation, int value, int Creates a scrollbar with the specified orientation,
extent, int min, int max) value, extent, minimum, and maximum.
Output:
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.
Constructor Description
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.
Methods Description
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.
Constructor Description
JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified arr
JComboBox(Vector<?> items) Creates a JComboBox that contains the elements in the specified Ve
Methods Description
void removeAllItems() It is used to remove all the items from the list.
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.
Constructor Description
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.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
Methods Description
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
Constructor Description
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.
Methods Description
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.
Output:
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.
Constructor Description
JPasswordField(String text, int Construct a new JPasswordField initialized with the specified
columns) text and columns.
Output:
The JColorChooser class is used to create a color chooser dialog box so that user can select
any color. It inherits JComponent class.
Constructor Description
Method Description
static Color showDialog(Component c, String title, Color It is used to show the color chooser
initialColor) dialog box.
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:
Java JFileChooser
The object of JFileChooser class represents a dialog window from which the user can select
file. It inherits JComponent class.
Constructor Description
• Java
• Java
• Java
Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and columns.
Constructor Description
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.
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.
Constructor Description
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.
Output:
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.
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.
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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
//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
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 Adapters:
Following is the list of commonly used adapters while listening GUI
events in AWT.
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.
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
DriverManager class
Blob class
Clob class
Types class
We can use JDBC API to handle database using Java program and can perform the following
activities:
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 −
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 −
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.
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:
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.
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.
Advantage:
Disadvantage:
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.
Advantage:
No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
Advantage:
Disadvantage:
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.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.
Class.forName("oracle.jdbc.driver.OracleDriver");
The getConnection() method of DriverManager class is used to establish connection with the database.
throws SQLException
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Statement stmt=con.createStatement();
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.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
con.close();
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.
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.
use demo;
import java.sql.*;
class MysqlCon{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/demo","root","root");
Statement stmt=con.createStatement();
while(rs.next())
con.close();
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,
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.
//Executing PreparedStatement
pstmt.executeUpdate();
//Executing PreparedStatement
pstmt.executeUpdate();
( "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.
register.html
Register.java
web.xml
register.html
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>
<option>India</option>
<option>Pakistan</option>
<option>other</option>
</select>
<br/><br/>
</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.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
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(
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
int i=ps.executeUpdate();
if(i>0)
out.close();
web.xml file
<web-app>
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<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>