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

AssignmentFile 571 27092023162548

1. The document discusses the AWT package in Java and its classes and interfaces for developing window applications. It describes the Frame class for creating windows and methods like setTitle(), setSize() etc. 2. It also discusses common components like Label, Button, TextField and their methods. It explains how to add components to containers using different layouts like BorderLayout, FlowLayout etc. 3. The document concludes with an overview of event handling in Java using the event delegation model and implementing listener interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views131 pages

AssignmentFile 571 27092023162548

1. The document discusses the AWT package in Java and its classes and interfaces for developing window applications. It describes the Frame class for creating windows and methods like setTitle(), setSize() etc. 2. It also discusses common components like Label, Button, TextField and their methods. It explains how to add components to containers using different layouts like BorderLayout, FlowLayout etc. 3. The document concludes with an overview of event handling in Java using the event delegation model and implementing listener interfaces.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 131

Unit-2

• Awt and applets


AWT
• AWT stands for abstract window toolkit. This is a built-
in package available in java package.
• This package provides all the tools (classes &
interfaces) that are required to develop any windows
applications in java.
• Therefore, this package must be imported in every
windows application program in java.
Class Hierarchy of AWT Package
Component Label

Container Button

Panel Window TextField

Frame List

Dialog …
Frame
• Frame is a container class that provides a window.
Whenever we are developing any window based
application, first of all we are required to create a
window.
• A window can be created by creating an object of
Frame class as follows :
Syntax: 1. Frame obj_name=new Frame();
2. Frame obj_name=new Frame(“title”);
Methods of Frame Class
1. setTitle() : This method is used to specify the title of a frame.
Syntax : Frame_objname.setTitle(“title”);
2. getTitle() : This method is used to retrieve the title of a frame.
Syntax : String objname=Frame_objname.getTitle();
3. setSize() : This method is used to specify the size(width, height) of a frame.
Syntax : Frame_objname.setSize(width,height);
4. show() : This method is used to show a window.
Syntax : Frame_objname.show();
5. hide() : This method is used to hide a frame.
Syntax : Frame_objname.hide();
6. setVisible() : This method is used to show/hide a frame.
Syntax : Frame_objname.setVisible(true/false);
7. dispose() : This method is used to release all the resources used by this frame , its sub
components and all of its own childen.
Syntax : Frame_objname.dispose();
8. setBackground() : This method is used to specify the bavkground color of a frame.
Syntax:
1. Frame_objname.setBackground(Color.COLORNAME);
2. Frame_objname.setBackground(Color objname);
9. setLocationRelativeTo(Component c) : This method is used to specify the
location of the window relative to the specified component. If the
component is not currently showing, or c is null, the window is centered on
the screen.
Syntax :
Frame_objname. setLocationRelativeTo(Component c) ;
Example1 : Develop a windows application having the title
MyWindow.
Components
• Components are the controls that are placed on a
container to design user interface.
• Java.awt package provides a separate class for every
component by inheriting Component class such as
Label, TextField, Button, List, Checkbox etc.
Label
• This class provides the component label that is used to
display text.
Syntax :
1. Label obj_name=new Label();
2. Label obj_name=new Label(“text”);
Methods of Label Class
1. setText() : This method is used to specify the text of a label.
Syntax : Label_objname.setText(“text”);
2. getText() : This method is used to retrieve the text of a label.
Syntax : String objname=Label_objname.getText();
3. setAlignment() : This method is used to specify the alignment of the text with respect
to label
Syntax : Label_objname.setAlignment(alignment);
4. getAlignment() : This method is used to retrieve the alignment of a label.
Syntax : int varname=Label_objname.getAlignment();
Adding Components to a Container
• Components can be added to a container in following
two ways :
1. According to Layout
2. According to User’s Specifications
1. Adding Components according to Layout
• According to layout, components can be added to a
container in following four ways, because there are four
types of layouts as follows:
A. BorderLayout
B. FlowLayout
C. CardLayout
D. GridLayout
A. Adding Components according to BorderLayout

• According to border layout, components are added on


the border of a container.
• According to border layout, at most five components
can be added to a container because there are only five
positions(East, West, North, South & Center) in border
layout.
• Center is the default position in border layout.
Steps for Adding Components According to BorderLayout

Step 1 : Create an object of BorderLayout class as follows :


BorderLayout Objname = new
BorderLayout ();
Step 2 : Set the layout of a container to BorderLayout as follows :
ContaineName.setLayout(BorderLayoutO

bjname);
Step 3 : Now, components can be added to a container by
calling add() of container class as follows :
ContainerObjname.add(CombonentName, position);
Example :
f.add(l1,BorderLayout.EAST);
f.add(l2,BorderLayout.North);
B. Adding Components according to FlowLayout

• According to flow layout, components are added in a


flow that can be left, right or center and any number of
components can added to a container.
Steps for Adding Components According to FlowLayout

Step 1 : Create an object of FlowLayout class as follows :


FlowLayout Objname = new
FlowLayout (flow);
Step 2 : Set the layout of a container to FlowLayout as follows :
ContaineName.setLayout(FlowLayoutO

bjname);
Step 3 : Now, components can be added to a container by
calling add() of container class as follows :
ContainerObjname.add(CombonentName);
Example :
f.add(l1);
f.add(l2);
C. Adding Components according to CardLayout

• According to card layout, components are added as


cards are placed that is one on another and therefore
only one component will be visible.
Steps for Adding Components According to CardLayout

Step 1 : Create an object of CardLayout class as follows :


CardLayout Objname = new
CardLayout ();
Step 2 : Set the layout of a container to CardLayout as follows :
ContaineName.setLayout(CardLayoutO

bjname);
Step 3 : Now, components can be added to a container by
calling add() of container class as follows :
ContainerObjname.add(CombonentName);
Example :
f.add(l1);
f.add(l2);
D. Adding Components according to GridLayout

• According to grid layout, components are added in a


grid (in the form of rows and columns that is tabular
format.).
Steps for Adding Components According to GridLayout

Step 1 : Create an object of GridLayout class as follows :


GridLayout Objname = new
GridLayout (rows,cols);
Step 2 : Set the layout of a container to GridLayout as follows :
ContaineName.setLayout(GridLayoutO

bjname);
Step 3 : Now, components can be added to a container by
calling add() of container class as follows :
ContainerObjname.add(CombonentName);
Example :
f.add(l1);
f.add(l2);
2. Adding Components according to User’s Specification

• While developing windows applications, most of the


time we are required to add components according to
user’s specification.
Steps for Adding Components According to User’s Specification

Step 1 : Every container has a layout by default.


Therefore, set the layout of a container to null as follows :
ContaineName.setLayout(null);
Step 2 : Now, specify the position & size of every component by
calling setBounds() of Component class as follows :
ComponentName.setBounds(left,top,width,height);
Step 3 : Now, components can be added to a container by
calling add() of container class as follows :
ContainerObjname.add(CombonentName);
Example :
f.add(l1);
f.add(l2);
TextField
• This class provides the component text box that is
used to get data from the user.
Syntax :
1. TextField obj_name=new TextField();
2. TextField obj_name=new TextField(“text”);
Methods of TextField Class
1. setText() : This method is used to specify the text of a text box.
Syntax : TextField_objname.setText(“text”);
2. getText() : This method is used to retrieve the contents/text of a text box.
Syntax : String objname=TextField_objname.getText();
3. setEditable() : This method is used to specify either the contents of a text
box can be edited or not directly.
Syntax : TextField_objname.setEditable(true/false);
4. isEditable() : This method returns true if text box is editable otherwise
returns false.
Syntax : boolean varname=TextField_objname.isEditable();
5. setEchoChar() : This method is used to specify a character that is to be
displayed instead of actual text.
Syntax : TextField_objname.setEchoChar(‘character’);
6. getEchoChar() : This method returna a character that is to be displayed.
Syntax : char varname=TextField_objname.getEchoChar();
Button
• This class provides the component command button
that can be used to start an action, suspend an action or
resume an action.
Syntax :
1. Button obj_name=new Button();
2. Button obj_name=new Button(“text”);
Methods of Button Class
1. setLabel() : This method is used to specify the text/caption of a button.
Syntax : Button_objname.setLabel(“text”);
2. getLabel() : This method is used to retrieve the caption/text of a button.
Syntax : String objname=Button_objname.getLabel();
Exercise1 : Develop a windows application to provide following
output.
Exercise2 : Develop a windows application to provide following
output.
Exercise3 : Develop Logon dialog box.
Event handling in Java
(Event Delegation Model)

• While working with java corresponding to every event


there is a class known as event class & corresponding
to every event class there is a Listener.
• A Listener is an interface that is used to handle events.
• Corresponding to every event class there is a separate
Listener available in java.awt.event package to handle
that particular event.
Steps To Perform Event Handling

Step 1 : Import the package java.awt.event as follows :


import java.awt.event.*;
Step 2 : Implements all the required Listeners as as follows :
class ClassName implemenmts ListenerName1,…
Step 3 : Now, bind all the components (for which event is
to be handled) with the required listener as follows :
ComponentName1.addListenerName(this);
ComponentName2.addListenerName(this);
………………………..
Step 4 : Now, Define all the methods of all the implemented
Listeners.
Event Handling of a Button
• Whenever a user clicks on a button, action event is
generated.
• Corresponding class to action event is ActionEvent
class.
• Corresponding Listener to ActionEvent class is
ActionListener.
• ActionListener consists of following method :
public void actionPerformed(ActionEvent objname)
List Class
• This class provides the component list box which
provides a list of choices from which a user can select
one or more choices.
Syntax :
1. List obj_name=new List();
2. List obj_name=new List(size);
3. List obj_name=new List(size,true/false);
Methods of List Class
1. add() : This method is used to add an item to a list box.
Syntax :
1. List_objname.add(“item”);
2. List_objname.add(“item”,index);
2. remove() : This method is used to remove an item from a list box.
Syntax : List_objname.remove(“item”/index);
3. removeAll() : This method is used to remove all items from a list box.
Syntax : List_objname.removeAll();
4. getItemCount() : This method counts the items of a list box .
Syntax : int varname=List_objname.getItemCount();
5. getSelectedItem() : This method returns the item selected by the user.
Syntax : String objname=List_objname.getSelectedItem();
6. getSelectedItems() : This method will work in case of multi select list box
only. This method returns all the items selected by the user.
Syntax : String[] objname=List_objname.getSelectedItems();
7. getSelectedIndex() : This method returns the index of the item selected by
the user.
Syntax : int Varname=List_objname.getSelectedItem();
7. getSelectedIndexes() : This method returns the index of all the items
selected by the user.
Syntax : int[] Varname=List_objname.getSelectedItem();
8. getItem() : This method is used to retrieve a particular item from a list box.
Syntax : String objname=List_objname.getItem(index);
9. Select() : This method is used to select an item in a list box.
Syntax : List_objname.Select(index);
10. isIndexSelected () : This method returns true if a particular item in a list box
is selected otherwise returns false.
Syntax : boolean Varname=List_objname.isIndexSelected(index);
Event Handling of a List Box
• A list box may generate following two types of events :
1. ActionEvent : This event is generated whenever a user
double clicks on an item of a list box. This event will be
handled same as previous.
2. ItemEvent : This event is generated whenever a user
single clicks on an item of a list box. This event will be
handled same as previous. Corresponding class to this
event is ItemEvent class and corresponding listener is
ItemListener to handle this event.
The interface ItemListener consists of following
method :
public void itemStateChanged(ItemEvent objname)
Exercise4 : Design following interface for a Book Shop :
Exercise5 : Design following interface for a Book Shop :
Choice Class
• This class provides the component combo box. A
combo box is also known as drop down list box that
provides a list of choices from which a user can select
only one choice at a time.
Syntax :
1. Choice obj_name=new Choice();
Methods of Choice Class
• Same as all methods of List class except multiselect family.
Events : Whenever a user clicks on an item of a combo box, item event is
generated that will be handled same as previous.
Example 1 : Develop a windows application having following
interface :
Checkbox Class
• This class provides the component check box.
• Checkboxes provides a list of choices from which a user
can select as many choices as he/she wants.
Syntax:
1. Checkbox obj_name=new Checkbox();
2. Checkbox obj_name=new Checkbox(“text”);
3. Checkbox obj_name=new Checkbox(“text”,true/false);
Methods of Checkbox Class
1. setLabel() : This method is used to specify the text of a check box.
Syntax : Checkbox_objname.setLabel(“text”);
2. getLabel() : This method is used to retrieve the text of a checkbox.
Syntax : String objname=Checkbox_objname.getLabel();
3. getState() : This method returns true if a check box is checked by the user
otherwise returns false.
Syntax : boolean varname=Checkbox_objname.getState();
4. setState() : This method is used to check or uncheck a check box.
Syntax : Checkbox_objname.setState(true/false);
Events of Checkbox Class

• Whenever a user clicks on a check box, item event is generated that will be
handled same as previous.
Example 1 : Develop a windows application having following
interface :
Radio Buttons
• They are also known as Option Buttons.
• Radio buttons provide a list of choices & from one
group of radio buttons, a user can select only one
choice at a time.
• Therefore, to work with radio buttons, we are required
to perform following two steps :
Step 1 : Creating a Group : To create a group,
CheckboxGroup class is used as follows :
Syntax: CheckboxGroup obj_name=new CheckboxGroup();
Step 2 : Creating Radio Buttons : After creating a group, radio buttons can be
created by creating(placing) checkboxes in the above created group as follows :
Syntax:
2. Checkbox obj_name=new Checkbox(“text”,GrpName);
3. Checkbox obj_name=new Checkbox(“text”,true/false,GrpName);
Example 1 : Develop a windows application having following
interface :
Scrollbar Class
• This class provides the component scroll
bar(Horizontal/Vertical).
• A scroll bar is used to get numeric data from the user
with in the given specific range.
Syntax:
1. Scrollbar obj_name=new Scrollbar();
2. Scrollbar obj_name=new Scrollbar(orientation);
3. Scrollbar obj_name=new Scrollbar(orientation, currentvalue, thumbsize,
minvalue, maxvalue);
Methods of Scrollbar Class
1. setOrientation() : This method is used to specify the orientation of a scrollbar.
Syntax :
Scrollbar_objname.setOrientation(Scrollbar.HORIZONTAL/Scrollbar.VERTICAL);
2. getOrientation) : This method is used to retrieve the orientation of a scrollbar.
Syntax : int varname=Scrollbar_objname.getOrientation();
3. setMinimum() : This method is used to specify the minimum value of the
scrollbar.
Syntax : Scrollbar_Objname.setMinimum(value);
4. getMinimum() : This method returns the minimum value of the scrollbar.
Syntax : int varname=Scrollbar_Objname.getMinimum();
5. setMaximum() : This method is used to specify the maximum value of the
scrollbar.
Syntax : Scrollbar_Objname.setMaximum(value);
6. getMaximum() : This method returns the maximum value of the scrollbar.
Syntax : int varname=Scrollbar_Objname.getMaximum();
7. setUnitIncrement() : This method is used to specify by what value, the value
of a scrollbar is to be increased/decreased whenever a user clicks on scroll
buttons.
Syntax : Scrollbar_Objname.setUnitIncrement(value);
8. getValue() : This method returns the current value of the scrollbar
Syntax : int Varname=Scrollbar_objname.getValue();
Events of Scrollbar Class

• Whenever a user clicks on scroll buttons in a scrollbar, adjustment event is


generated. Corresponding class to adjustment event is AdjustmentEvent class
& corresponding listener is AdjustmentListener.
• AdjustmentListener interface consists of following method :
public void adjustmentValueChanged(AdjutmentEvent Objname)
Example 1 : Design Color Dialog Box having following interface :
Example 2 : Design Temperature Converter having following interface :
Working With Menus
• While developing windows application, it must be user
friendly.
• A windows application can be made more user friendly
by providing menus.
• Java provides following three classes to work with
menus :
1. MenuBar
2. Menu
3. MenuItem
1. MenuBar Class
• This class provides the component menu bar.
• A menu bar is a horizontal line just below the title bar.
• A menu bar consists of one or more menus.
Syntax:
MenuBar obj_name=new MenuBar();
Methods of Menubar Class
1. add() : This method is used to add a menu to a menu bar.
Syntax : MenuBar_objname.add(Menu_Objname);
2. Menu Class
• This class provides the component menu.
• A menu is a pad that is displayed on a menu bar.
• A menu consists of one or more menu items.
Syntax:
Menu obj_name=new Menu(“text/caption”);
Methods of Menu Class
1. add() : This method is used to add a menu item to a menu.
Syntax : Menu_objname.add(MenuItem_Objname);
2. addSeparator() : This method is used to add a separataaor line to a menu at
the current position.
Syntax : Menu_objname.addSeparator();
2. MenuItem Class
• This class provides the component menu item.
• A menu item is a command that is used to perform a
particular task.
Syntax:
1. MenuItem obj_name=new MenuItem(“text/caption”);
2. MenuItem obj_name=new MenuItem(“text”, MenuShortcut Objname);
Note : MenuShortcut ms = new MenuShortcut (KeyEvent.VK_A, false);
Methods of MenuItem Class
1. setEnabled() : This method is used to enable/disable a menu item..
Syntax : MenuItem_objname.setEnabled(true/false);

Events of MenuItem Class


• Whenever a user clicks on a menu item, Action Event is generated, that will be
handled same as previous.

Note : After creating a MenuBar, Menus & MenuItems, the MenuBar is to be set
on a Frame(container) as follows :
Frame_Objname.setMenuBar(MenuBar_Objname);
Example 1 : Design a windows application having following interface :
General Events
1. Key Events
2. Mouse Events
3. Window Events
1. Key Events
• Key events are generated whenever we perform any
operation with the key board such as pressing a key,
releasing a key etc.
• Key Events are used to trap a key.
• Corresponding class to key events is KeyEvent class &
corresponding listener is KeyListener.
Methods of KeyListener

1. public void keyPressed(KeyEvent Objname)

2. public void keyReleased(KeyEvent Objname)

3. public void keyTyped(KeyEvent Objname)


2. Mouse Events
• Mouse events are generated whenever we perform
any operation with the mouse such as pressing a
mouse button, releasing a mouse button, clicking a
mouse button etc.
• Corresponding class to mouse events is MouseEvent
class & corresponding listener is MouseListener.
Methods of MouseListener

1. public void mousePressed(MouseEvent Objname)

2. public void mouseReleased(MouseEvent Objname)

3. public void mouseClicked(MouseEvent Objname)

4. public void mouseEntered(MouseEvent Objname)

5. public void mouseExited(MouseEvent Objname)


3. Window Events
• Window events are generated whenever we perform
any operation with the window such as opening a
window, closing a window, minimizing a window etc.
• Corresponding class to window events is WindowEvent
class & corresponding listener is WindowListener.
Methods of WindowListener

1. public void windowOpened(WindowEvent Objname)

2. public void windowActivated(WindowEvent Objname)

3. public void windowDeactivated(WindowEvent Objname)

4. public void windowIconified(WindowEvent Objname)

5. public void windowDeiconified(WindowEvent Objname)

6. public void windowClosing(WindowEvent Objname)

7. public void windowClosed(WindowEvent Objname)


String Handling
(Working with Strings)

• As we already know a string is a collection/sequence of


characters.
• There is no primitive data type provided by java to
work with strings.
• Java provides following classes to work with strings :
1. String
2. StringBuffer
3. StringTokenizer
1. String Class
• String is a built-in class available in java.lang package.
• This class provides the mechanism to
manipulate(work) a string.
• String objects are immutable i.e. their value can not be
changed after they are created.
• A String object can be created in the following ways :
1. String objname = “string“;

2. String objname = new String();

3. String objname = new String(“string”);


4. String objname = new String(char aryname);

5. String objname = new String(byte aryname);


6. String objname = new String(StringBuffer objname );
Methods of String Class
1. toLowerCase() : This method is used to convert a string into lower case.
Syntax : String_objname2=String_objname1.toLowerCase();
2. toUpperCase() : This method is used to convert a string into upper case
Syntax : String_objname2=String_objname1.toUpperCase();
3. length() : This method is used to claculate the length of a string.
Syntax : int varname=String_Objname.length();
4. charAt() : This method is used to extract a character from the specific given
position.
Syntax : char varname=String_Objname.charAt(index);
5. getChars() : This method is used to extract specific no. of characters from the
specific given position.
Syntax : String_Objname.getChars(start_pos, end_pos, char_aryname,
destination_position);
6. substring() : This method is used to extract a substring from a string.
Syntax :
7. String_objname2=String_objname1.substring(start_pos);
8. String_objname2=String_objname1.substring(start_pos, end_postion);
7. equals() : This method is used to compare two strings and returns true if
both the strings are identical otherwise returns false.
Syntax : boolean varname=String_Objname1.equals(String_Objname2);
8. compareTo() : This method is used to compare two strings and may return
one of the following values :
0 => if both strings are identical
< 0 => if string1 comes earlier than string2
> 0 => if string1 comes later than string2
Syntax : int varname=String_Objname1.compareTo(String_objname2);
9. indexOf() : This method is used to search a character/substring with in a
string. If found, returns the position of the first occurrence of the searched
text otherwise returns -1.
Syntax :
int varname=String_objname.indexOf(‘char’/”string”);
10. lastIndexOf() : Same if indexOf() except that returns the position of the last
occurrence of the searched text.
Syntax :
int varname=String_objname.lastIndexOf(‘char’/”string”);
11. toCharArray() : This method is used to convert a string to a character array.
Syntax : char[] Aryname=String_objname.toCharArray();
12. valueOf() : This is a static method of String class that is used to convert any type of data
into the equivalent string representation.
Syntax : String_objname=String.valueOf(any varname);
13. getBytes() : This method is used to encode a string into a sequence of bytes.
Syntax : byte[] Aryname=String_objname.getBytes();
Exercise
Write a program to get a string from the user. Display string in lower case, upper case and
proper case.
Write a program to get a string from the user. Check either it is palindrome or not.
Write a program to get your full name. Display sir name only.
Write a program to get your full name. Display initials only.
Example 1:
Input => Amit Kumar Sharma
Output : A.K. Sharma

Example 2:
Input => Amit Sharma
Output : A. Sharma

Example 3:
Input => Amit
Output : A.
Example 1 : Design a windows application having following interface :
JDBC
• JDBC stands for Java Database Connectivity which is a
standard Java API for database-independent
connectivity between the Java programming language
and a wide range of databases.
• It is a part of JavaSE (Java Standard Edition).
• JDBC API uses JDBC drivers to connect with the
database.
JDBC Drivers
• JDBC Driver is required to establish connection between application and
database. It also helps to process SQL requests and generating result.
• The following are the different types of driver available in JDBC which are used
by the application based on the scenario and type of application.
• Type-1 Driver or JDBC-ODBC bridge
• Type-2 Driver or Native API Partly Java Driver
• Type-3 Driver or Network Protocol Driver
• Type-4 Driver or Thin 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.
• 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:
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is converted into the ODBC function
calls.
• The ODBC driver needs to be installed on the client machine.
2. Native-API driver (partially java 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:
• 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 (fully java 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.
• 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 (fully java 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.
• Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
• Disadvantage:
• Drivers depend on the Database.
Steps to Connect to database in Java

• There are 5 steps to create a connection with a


database in Java :
1. Register the driver class
2. Create the connection
3. Create a statement
4. Execute queries/statement
5. Close the connection
1. Register the driver class
The forName() method of the Class class registers the driver class.
Syntax :
public static void forName(String classname) throws ClassNotFoundException
Example :
1. To Connect to oracle
Class.forName("oracle.jdbc.driver.OracleDriver");
2. To Connect to mysql
Class.forName("com.mysql.jdbc.Driver");
2. Create the connection object
The getConnection() method of the DriverManager class establishes the
connection with the database.
Syntax
public static Connection getConnection(String url) throws Exception
OR
public static Connection getConnetion(String name, String url, String password)
Example 1. To Connect to oracle
Connection conn=DriverManager.getConnection
("jdbc.oracle.thin:@localhost:xe","username","password");
OR
Connection conn=DriverManager.getConnection
("jdbc:oracle:thin:username/password@localhost:1521:xe");
Example 2. To Connect to mysql
Connection conn=DriverManager.getConnection
("jdbc:mysql://localhost/dbname","username","password");
3. Create the Statement object
The createStatement() method of the Connection interface is used to create the
statement. This object is responsible for executing SQL statements with the
database.
Syntax
public Statement createStatement() throws Exception
Example
Statement stm=conn.createStatement();
4. Execute SQL Statement
Statement interface provides following two methods to execute sql statements
with the databse :
1. executeUpdate()
2. executeQuery()

1. executeUpdate() : This method can be used to execute insert, update or delete


statement to update the database.
Syntax
Public int executeUpdate(String cmd) throws Exception
Example
stm.executeUpdate(“insert into tname values(v1,v2,...)”);
2. executeQuery() : This method is used to execute select statement to retrieve
data from the database.
Syntax
Public ResultSet executeQuery(String cmd) throws Exception
Example
ResultSet rs=stm.executeQuery(“select * from tname”);
5. Close the connection object
• By closing the connection object the statement and ResultSet will be closed
automatically. The close() method of the Connection interface closes the
connection.
Syntax
public void close() throws Exception
Example
conn.close();
=
Applet
• Literally an applet means “A Small Application”.
• Applet is a special type of program that is embedded in
the webpage to generate the dynamic content.
• It runs inside the browser and works at client side.
Advantage of Applet
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many
plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
• Plugin is required at client browser to execute applet.
The Applet Class
• To design an applet(small internet application) java
provides a built-in class Applet having following class
hierarchy :
Applet Skeleton
• An applet has four distinct stages in its life time.
• Each of these stages includes methods that are called
in the order in an applet’s life cycle.
• These methods are as follows :
Applet Skeleton
• An applet has four distinct stages in its life time.
• Each of these stages includes methods that are called in
the order in an applet’s life cycle.
• These methods are as follows :
1. public void init(): This stage consists of initializing
methods & variables that the applet need to function.
This is the first method which is called when an applet is
loaded. It is invoked only once.
2. public void start(): This stage starts the primary function
of an applet. This method is invoked after the init()
method. It is used to start the Applet.
3. public void stop(): This is used to stop the Applet. It is
invoked when Applet is stop or browser is minimized.
4. public void destroy(): This is used to destroy the Applet.
It is invoked only once.
Life Cycle of An Applet
• In the life cycle of an applet, following two types of
methods are executed in following sequence :
1. Initialization Methods : When an applet is loaded the initialization methods
init(), start() and paint() methods are executed in following sequence :
init()  start()  paint()
2. Termination Methods : When an applet is terminated the methods stop(),
destroy() are executed in following sequence :
start()  destroy()
Working With Applet
• To work with an applet, we are required to perform
following two steps :
1. Developing an Applet
2. Running an Applet
1. Developing An Applet
• To develop an applet, we are required to create a java
file consists of java code.
• Therefore, we are required to perform following steps to
create an applet program:
1. Import all the required packages as follows :
import java.applet.*;
import java.awt.*;
……………………….. ;
2. Now, define a public class by inheritig Applet class as
follows :
public class ClassName extends Applet
3. Now, override all of the required life cycle methods
(init(), start(), paint(), stop() & destroy()) of Applet
class in the above defined class.
4. Now, save & compile your Applet program same as
normal java program.
2. Running An Applet

• There are two ways to run an applet


A. By html file.
B. By appletViewer tool (for testing purpose).
A. Running An Applet by HTML File
• To run an applet using this method create an html file
having following code:
<html>
<applet code=“classname”
codebase=“path of class file”
height=“h”
width=“w”
alt=“alternate text”
align=“alignment”
name=“appletname”>
<param name=“name” value=“value”>
</applet>
</html
B. Running An Applet using Applet Viewer
• To execute the applet by appletviewer tool, create an
applet that contains following applet tag in comment
and compile it.
<applet code=“classname” height=“h” width=“w”>
</applet>
• After that run it by issuing following command at
command prompt :
appletviewer Programname.java.
• Example : Develop an applet to display “Welcome To Applet”.
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welome To Applet”,50,50);
}
}
Displaying Graphics in Applet
• java.awt.Graphics class provides many methods for graphics programming.
• Commonly used methods of Graphics class are as follows:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
3. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with
the specified width and height.
4. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between
the points(x1, y1) and (x2, y2).
5. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
6. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with
the default color and specified width and height.
7. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the
default color and specified width and height.
8. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
9. public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
10. public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
• Example of Graphics in applet:
/* <applet code="GraphicsDemo" height=600 width=600> </applet> */
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.blue);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);

You might also like