Upload
amir-khan
View
227
Download
0
Embed Size (px)
Citation preview
7/30/2019 Object Oriented Technic Notes(Unit5)
1/30
ECSECSECSECS----503: Object Oriented Techniques503: Object Oriented Techniques503: Object Oriented Techniques503: Object Oriented Techniques
UnitUnitUnitUnit ---- VVVV
Introduction to AWTIntroduction to AWTIntroduction to AWTIntroduction to AWT ::::
Abstract Window Toolkit (AWT) is a set of application program interfaces (API s) used byJava programmers to create graphical user interface ( GUI ) objects, such as text fieldsbuttons, toggle buttons, scroll bars, windows, and menus.
AWT contains several graphical widgets which can be added and positioned to the displayarea with a layout manager.
AWT API was introduced in JDK 1.0. It contains all classes to write the program that interface between the user and different
windowing toolkits.
The AWT is now part of the Java Foundation Classes (JFC) the standard API for providinga graphical user interface (GUI) for a Java program.
It is a portable GUI library for stand-alone applications and/or applets. AWT features include:AWT features include:AWT features include:AWT features include:
A rich set of user interface components. A robust event-handling model. Graphics and imaging tools, including shape, color, and font classes. Layout managers, for flexible window layouts that don't depend on a particular window size
or screen resolution.
Create windows and menus for standalone Java applications. Components of AWT:Components of AWT:Components of AWT:Components of AWT:
1.1.1.1. Container.Container.Container.Container.Containers (such as Frame, Panel and Applet) are used to hold components(suchas Button, Label, and TextField.) in a specific layout .
2.2.2.2. CaCaCaCanvases.nvases.nvases.nvases. It is a simple drawing surface. Canvases are good for painting images or othergraphics operation....
3.3.3.3. UI component:UI component:UI component:UI component:These can include buttons, lists, simple popup menus, checkboxes, test fieldsand other typical elements of a user interface.
4. Window construction components:Window construction components:Window construction components:Window construction components: These include windows, frames, menubars, and dialogsThese are listed separately from the other User Interface components (UI components) .
7/30/2019 Object Oriented Technic Notes(Unit5)
2/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
2
AWT PackagesAWT PackagesAWT PackagesAWT Packages::::
AWT consists of 12 packages (Swing is even bigger, with 18 packages as of JDK 1.7). Fortunately, only
2 packages - java.awt and java.awt.event - are commonly-used.
1.1.1.1. The java.awtjava.awtjava.awtjava.awt packagepackagepackagepackage contains the coreAWT graphics classes:
GUI Component classes (such as Button, TextField, and Label), GUI Container classes (such as Frame, Panel, Dialog and ScrollPane), Layout managers (such as FlowLayout, BorderLayout and GridLayout), Custom graphics classes (such as Graphics, Color and Font).
2.2.2.2. The java.awt.eventjava.awt.eventjava.awt.eventjava.awt.event package supports event handling: Event classes (such as ActionEvent, MouseEvent, KeyEvent and WindowEvent), Event Listener Interfaces (such as ActionListener, MouseListener, KeyListener and
WindowListener),
Event Listener Adapter classes (such as MouseAdapter, KeyAdapter,and WindowAdapter).
AWT Class HierarchyAWT Class HierarchyAWT Class HierarchyAWT Class Hierarchy::::
ComponentComponentComponentComponent:::: Java's Abstract Windowing Toolkit provides many of the user interface objects we
find in the Windows environment. These are called "Components" of the Java AWT. Component is
an abstract class that encapsulates all of the attributes of a visual component.
7/30/2019 Object Oriented Technic Notes(Unit5)
3/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
3
Basic User Interface Component (UI Component):Basic User Interface Component (UI Component):Basic User Interface Component (UI Component):Basic User Interface Component (UI Component):
Label:Label:Label:Label: This component is generally used to show the text or string in your application andlabel never perform any type of action. Class Label has following constructors :
Label():Label():Label():Label(): creates an empty label with its text aligned left.
Label(String):Label(String):Label(String):Label(String): create a label with the given text string, also aligned left.
Label(String, int):Label(String, int):Label(String, int):Label(String, int): create a label with the given text string and the given alignment.
Label label_Name = new Label(This is label text);
Button:Button:Button:Button: Button are simple UI components that trigger some action in your interface whenthey are pressed. Class Button has following constructors :
Button():Button():Button():Button(): create an empty button with no label.
Button(String):Button(String):Button(String):Button(String): create a button with the given string object as a label.
Button button_Name = new Button(This is button label);
CheckCheckCheckCheckBox:Box:Box:Box: This component is used to create check boxes in your application. Checkboxeshave two states on and off. (or checked and unchecked or selected and
unselected or true and false).
Checkbox():Checkbox():Checkbox():Checkbox(): create an empty checkbox, unselected.
Checkbox(String):Checkbox(String):Checkbox(String):Checkbox(String): create a checkbox with the given string as a label.
Checkbox(String, null, Boolean):Checkbox(String, null, Boolean):Checkbox(String, null, Boolean):Checkbox(String, null, Boolean): create a checkbox with the given string and given
Boolean value(true/false).
Checkbox checkbox_Name = new Checkbox(Red);
Radio ButtonRadio ButtonRadio ButtonRadio Button:::: This is the special case of the Checkbox component. This is used as agroup of checkboxes which group name is same. Only one Checkbox from a Checkbox
group can be selected at a time. Create an instance of CheckboxGroup class.
CheckboxGroup color = new CheckboxGroup();
Create a Checkbox instance and pass firstfirstfirstfirst argument value of Checkbox,secondsecondsecondsecond argument instance of CheckboxGroup (color),
thirdthirdthirdthird argument ture/false.(true for selected and false for unselected).
Checkbox checkbox_Name = new Checkbox(Red, color, ture);
7/30/2019 Object Oriented Technic Notes(Unit5)
4/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
4
ChChChChoice Menus:oice Menus:oice Menus:oice Menus: Choice menus are popup (or pulldown) menus that enable you to selectan item from that menu. The menu then displays that choice in the screen. To create a
choice menu, create an instance of the Choice class, and then use the addItem() method to
add individual items to it in the order in which they should appear:
Create an instance of Choice class.
Choice college=new Choice();Add item of Choice class.
college.addItem("UIT);
college.addItem("UCER);
college.addItem("UIM);
college.addItem("IIIT);
Text Fields:Text Fields:Text Fields:Text Fields: Text Fields allow you to enter any values.TextField():TextField():TextField():TextField(): Create an empty TextField 0 characters wide.
TextField(int):TextField(int):TextField(int):TextField(int): Create an empty text field with the given width characters.
TextField(String, int):TextField(String, int):TextField(String, int):TextField(String, int): Create a text field with the give width in characters and
containing the given string.
TextField comment=new TextField("Enter you facebook comment,35);
PasswordPasswordPasswordPasswordFields:Fields:Fields:Fields: Password Fields allow you to enter any values and that does not echocharacters you entered.
PasswordPasswordPasswordPasswordField(int):Field(int):Field(int):Field(int): Create an empty text field with the given width characters.
PasswordField pwd = new PasswordField(25);
7/30/2019 Object Oriented Technic Notes(Unit5)
5/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
5
Layout Managers:Layout Managers:Layout Managers:Layout Managers: A layout manager is an object that controls the size and position (layout) ofcomponents inside a Container object. For example, a window is a container that contains
components such as buttons and labels.
FlowLayoutFlowLayoutFlowLayoutFlowLayout ---- FlowLayout is the default layout manager for all Panels. It simply lays outcomponents from left to right in a row. If the row is full, it arranges in the next row from left
to right. FlowLayout: Default FlowLayout, which centers components and leaves five pixels of
space between each component.
FlowLayout(int how): Create aFlowLayout with the given
alignment value.
FlowLayout.LEFTFlowLayout.LEFTFlowLayout.LEFTFlowLayout.LEFT
FlowLayout.CENTERFlowLayout.CENTERFlowLayout.CENTERFlowLayout.CENTER FlowLayout.RIGHTFlowLayout.RIGHTFlowLayout.RIGHTFlowLayout.RIGHT
BorderLayBorderLayBorderLayBorderLayoutoutoutout - BorderLayout is the default layout manager for all Windows, such asFrames and Dialogs. It uses five areas to hold components: north, south, east, west, and center
All extra space is placed in the center area.
BorderLayout() : Create adefault border layout.
BorderLayout( int horz, intvert): Create a border layout to
specify the horizontal and
vertical space left between
components in horz and vert,
respectively.
Specify the Regions: BorderLaBorderLaBorderLaBorderLayyyyout.CENTERout.CENTERout.CENTERout.CENTER BorderLaBorderLaBorderLaBorderLayyyyout.EASTout.EASTout.EASTout.EAST BorderLaBorderLaBorderLaBorderLayyyyout.WESTout.WESTout.WESTout.WEST BorderLaBorderLaBorderLaBorderLayyyyout.NORTHout.NORTHout.NORTHout.NORTH BorderLaBorderLaBorderLaBorderLayyyyout.SOUTHout.SOUTHout.SOUTHout.SOUTH
7/30/2019 Object Oriented Technic Notes(Unit5)
6/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
6
CardLayoutCardLayoutCardLayoutCardLayout CardLayout are used toproduce slide shows of components, one
at a time. The components are treated
like a stack of cards with only one
component visible at a time.
CardLauout(): Creates a newcard layout with gaps (pixel
space between each components)
of size zero.
CardLayout(int horz, int vert):Creates a new card layout with the specified horizontaand vertical gaps.
GridLayoutGridLayoutGridLayoutGridLayout ---- The container is divided up into identically sized spaces. The components areplaced from top left to right going
down. Unlike FlowLayout, every
component gets any equal area even
if they are different sizes.
GridLayout() : Creates a gridlayout with a default of one
column per component, in a
single row. GridLayout(int rows,
int cols) : Creates a grid layout with the specified number of rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap) : Creates a grid layout with thespecified number of rows and columns.
7/30/2019 Object Oriented Technic Notes(Unit5)
7/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
7
Event Handling Mechanism:Event Handling Mechanism:Event Handling Mechanism:Event Handling Mechanism: GUI applications are event-driven programs. Event handlingis at the core of successful GUI programming. Most events to which a GUI application will respond
are generated by the user.
The Delegation Event Model:The Delegation Event Model:The Delegation Event Model:The Delegation Event Model: The modern approach to handling events is based on the
delegation event model. A source generates an event and sends it to one or more listeners. The
listener simply waits until it receives an event. Once received, the listener processes the event and
then returns. The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events
EventEventEventEvent:::: An event is an object that describes a state change in a source.
Event Source:Event Source:Event Source:Event Source: A source is an object that generates an event.
Event Listeners:Event Listeners:Event Listeners:Event Listeners: A listener is an object that is notified when an event occurs. It has two
major requirements. First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to receive and
process these notifications.
7/30/2019 Object Oriented Technic Notes(Unit5)
8/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
8
Type of AWT EVENTType of AWT EVENTType of AWT EVENTType of AWT EVENT
These events are used to make the application more effective and efficient. Generally, there are
twelve types of event are used in Java AWT.
1. ActionEvent:ActionEvent:ActionEvent:ActionEvent: It indicates the component-defined events occurred i.e. the event generated bythe component like Button, Checkboxes etc. The generated event is passed to every
EventListener objects.
2. AdjustmentEvent:AdjustmentEvent:AdjustmentEvent:AdjustmentEvent: When the Adjustable Value is changed then the event is generated.3. FocusEvent:FocusEvent:FocusEvent:FocusEvent: This class indicates about the focus where the focus has gained or lost by the
object.
4. ItemEventItemEventItemEventItemEvent:::: The ItemEvent class handles all the indication about the selection of the object i.ewhether selected or not.
5. KeyEventKeyEventKeyEventKeyEvent: The KeyEvent class handles all the indication related to the key operation in theapplication if you press any key for any purposes of the object then the generated event gives
the information about the pressed key.
6. MouseEvent:MouseEvent:MouseEvent:MouseEvent: . The MouseEvent class handle all events generated during the mouse operationfor the object. That contains the information whether mouse is clicked or not if clicked then
checks the pressed key is left or right.
7. WindowEvent :WindowEvent :WindowEvent :WindowEvent : If the window or the frame of your application is changed (Opened, closedactivated, deactivated or any other events are generated), WindowEvent is generated.
AdaAdaAdaAdapter Class:pter Class:pter Class:pter Class: Java provides a special feature called an adapter class that can simplifythe creation of event handlers in certain situations. An adapter class provides an empty
implementation of all method in an event Listener interface. Adapter class is useful when you
want to receive at process only some of event that is handled by a particular event Listener
interface. For example Mouse motion adapter class has two method mouse drag & mouse
move. This signature of these empty methods exactly defines the mouse motion Listener
interface.
7/30/2019 Object Oriented Technic Notes(Unit5)
9/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
9
Steps for implementing Event HaSteps for implementing Event HaSteps for implementing Event HaSteps for implementing Event Handling :ndling :ndling :ndling :1)1)1)1) ImImImImporting java.awt.event packageporting java.awt.event packageporting java.awt.event packageporting java.awt.event package;;;;
event package is a subpackage of java.awt package that have Listener interfaces for all type of
events, also includes their respective Adapter classes.
2)2)2)2) ImplementingImplementingImplementingImplementing Listener Interface or extending Adapter ClassListener Interface or extending Adapter ClassListener Interface or extending Adapter ClassListener Interface or extending Adapter Class....class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//Perform Task Here
}
}
Similarly we can implement any type of Event listener like ActionListener, MouseListener
KeyListener, WindowListener etc, or we can extend Adapter Classes like MouseAdapter
KeyAdapter, WindowAdapter etc.
3)3)3)3) Registering implemented Listener to event source.Registering implemented Listener to event source.Registering implemented Listener to event source.Registering implemented Listener to event source.Button b1 = new Button("ADD");
Button b2 = new Button("SUB");
//instantiating Event Handler
ActionHandler ah = new ActionHandler();
//Registering instantiated handler to event sources.
b1.addActionListener(ah);
b2.addActionListener(ah);
7/30/2019 Object Oriented Technic Notes(Unit5)
10/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
10
ExampleExampleExampleExample : GUI Calculator: GUI Calculator: GUI Calculator: GUI Calculator import java.awt.*;
import java.awt.event.*;
publicpublicpublicpublic classclassclassclass CalculatorCalculatorCalculatorCalculator extendsextendsextendsextends FrameFrameFrameFrame implementsimplementsimplementsimplements ActionListenerActionListenerActionListenerActionListener {{{{
TextField t1, t2, t3;
Label l1, l2, l3;Button b1, b2;
publicpublicpublicpublic Calculator()Calculator()Calculator()Calculator() {{{{
setSize(250,200);
setVisible(true);
setTitle("CALC");
setBackground(Color.GRAY);
//Setting Flowlayout on Calculator Frame
setLayout(new FlowLayout(FlowLayout.CENTER));
//For Window Close Operation
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0); }});
t1 = new TextField(20);
t2 = new TextField(20);
t3 = new TextField(20);
b1 = new Button("ADD");
b2 = new Button("SUB");
b1.addActionListener(this);
b2.addActionListener(this);
l1 = new Label("Number One");
l2 = new Label("Number Two");
l3 = new Label("OPR RESULT");
7/30/2019 Object Oriented Technic Notes(Unit5)
11/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
11
add(l1); add(t1); add(l2); add(t2);
add(l3); add(t3); add(b1); add(b2);
}}}} //End Of Constructor//End Of Constructor//End Of Constructor//End Of Constructor
public void actionPerformed(ActionEvent ae)public void actionPerformed(ActionEvent ae)public void actionPerformed(ActionEvent ae)public void actionPerformed(ActionEvent ae) {{{{
if(ae.getSource() == b1) {
int n1 = Integer.parseInt(t1.getText());int n2 = Integer.parseInt(t2.getText());
int sum = n1 + n2;
t3.setText(String.valueOf(sum));
}
if(ae.getSource() == b2) {
int n1 = Integer.parseInt(t1.getText());
int n2 = Integer.parseInt(t2.getText());int sum = n1 - n2;
t3.setText(String.valueOf(sum));
}
}}}} //End Of Handler Method//End Of Handler Method//End Of Handler Method//End Of Handler Method
}}}}//End Of Calculator Class//End Of Calculator Class//End Of Calculator Class//End Of Calculator Class
class GUIDemo {class GUIDemo {class GUIDemo {class GUIDemo {
public static void main(String [] ar) {public static void main(String [] ar) {public static void main(String [] ar) {public static void main(String [] ar) {
Calculator c = new Calculator();
}}}}//End Of Main Method//End Of Main Method//End Of Main Method//End Of Main Method
}}}}//End Of GUI Demo//End Of GUI Demo//End Of GUI Demo//End Of GUI Demo
Output :Output :Output :Output :
C:C:C:C:\\\\UnitedUnitedUnitedUnited\\\\CS>javac GUIDemo.jCS>javac GUIDemo.jCS>javac GUIDemo.jCS>javac GUIDemo.javaavaavaava
C:C:C:C:\\\\UnitedUnitedUnitedUnited\\\\CS>java GUIDemoCS>java GUIDemoCS>java GUIDemoCS>java GUIDemo
7/30/2019 Object Oriented Technic Notes(Unit5)
12/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
12
Swing:Swing:Swing:Swing: Swing is part of the "Java Foundation Classes (JFC)", which was introduced in 1997 afterthe release of JDK 1.1. Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI
components that can be dragged and dropped as "GUI builders" in visual programming environment
Swing is now an integral part of Java since JDK 1.2. An effort to incorporate many of the features in Netscape's IFC as well as some aspects of IBM
stuff
First released in March of 1998 with nearly 250 classes and 80 interfaces. Advanced graphical programming. Provides assistive technology for the disabled. High quality 2D graphics and images. Pluggable look and feel supports. Drag-and-drop support between Java and native applications. Swing is not a replacement for the AWT.
- Needed to support truly architecture independent interfaces
- Contains more powerful components
Why bother?- Increased acceptance (many more supported architectures)
- AWT based on architecture-specific widgets.
Swing FeatuSwing FeatuSwing FeatuSwing Featuresresresres::::
Pluggable Look and FeelPluggable Look and FeelPluggable Look and FeelPluggable Look and Feel:::: The Look and Feel that means the dramatically changing in thecomponent like JFrame, JWindow, JDialog etc. for viewing it into the several type of window.
LnFs are increasingly important Similar look of underlying environment LnFs for UNIX, Windows, Apple. (Default is called Metal) LnFs can be changed at run-time
Lightweight ComponentsLightweight ComponentsLightweight ComponentsLightweight Components:::: Lightweight - components which are not dependent on native source to render Heavyweights are unwieldy because:
- Equivalent components may act differently on different platforms
- LnF is tied to the host environment
7/30/2019 Object Oriented Technic Notes(Unit5)
13/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
13
Many new ComponentsMany new ComponentsMany new ComponentsMany new Components Tables Trees Sliders Progress Bars Internal Frames Text Components (Very nice) Tool tips Support for undo/redo Support for Multiple Document Interfaces (MDI) with InternalFrames.
Swings Component :Swings Component :Swings Component :Swings Component :
7/30/2019 Object Oriented Technic Notes(Unit5)
14/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
14
SwingSwingSwingSwing Vs.Vs.Vs.Vs. AWTAWTAWTAWT::::
S. No.S. No.S. No.S. No.Point ofPoint ofPoint ofPoint of
comparisoncomparisoncomparisoncomparisonSwingSwingSwingSwing AWTAWTAWTAWT
1111 SpeedSpeedSpeedSpeed Swing component are generally
slower and buggier than AWT, due to
both the fact that they are pure javaand to video issues on various
platforms.
Use of native peers speeds component
performance.
2222 Applet PortabilityApplet PortabilityApplet PortabilityApplet Portability Most web browsers do not include the
swing classes, so the java plugin must
be used.
Most web browser support AWT
classes so AWT applets can run
without the java plugin
3333 PortabilityPortabilityPortabilityPortability Pure java design provides for fewer
platform specific limitations
Use of native peers creates platform
specific limitations. Some components
may not function at all on some
platforms.
4444 Look and FeelLook and FeelLook and FeelLook and Feel The pluggable look and feel lets you
design a single set of GUI components
that can automatically have the look
and feel of any OS platform.
AWT component more closely reflect
the look and feel of the OS they run
on.
5555 Third partyThird partyThird partyThird party
DevelopmentDevelopmentDevelopmentDevelopment
Swing development is more active.
Sun puts much more energy into
making swing robust.
The majority of component makers,
base new component development on
swing components. There is a much
smaller set of AWT components
available, thus placing the burden in
the programmer to create his or her
own AWT based component.
6666 FeatureFeatureFeatureFeature Swing supports a wider range offeature like icons and pop-up tool-
tips for components.
AWT components do not supportfeature like icons and tool-tips.
7/30/2019 Object Oriented Technic Notes(Unit5)
15/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
15
Java as an Internet Language:Java as an Internet Language:Java as an Internet Language:Java as an Internet Language: Java is an object oriented language and a very simplelanguage. Because it has no space for complexities. At the initial stages of its development it was
called as OAK. OAK was designed for handling set up boxes and devices. But later new features were
added to it and it was renamed as Java. Java became a general purpose language that had many
features to support it as the internet language. Few of the features that favors it to be an internet
language are:
Cross Platform Compatibility:Cross Platform Compatibility:Cross Platform Compatibility:Cross Platform Compatibility: The java source files (java files with .java extension) aftercompilation generate the bytecode (the files with .class extension) which is further converted into
the machine code by the interpreter. The byte code once generated can execute on any machine
having a JVM. Every operating system has it's unique Java Virtual Machine (JVM) and the Java
Runtime Environment (JRE).
Support to Internet Protocols:Support to Internet Protocols:Support to Internet Protocols:Support to Internet Protocols: Java has a rich variety of classes that abstracts the Interneprotocols like HTTP, FTP, IP, TCP-IP, SMTP, DNS etc .
Support to HTML:Support to HTML:Support to HTML:Support to HTML: Most of the programming languages that are used for web application usesthe html pages as a view to interact with the user. Java programming languages provide its
support to html.
Support to Java Reflection APIs:Support to Java Reflection APIs:Support to Java Reflection APIs:Support to Java Reflection APIs: To map the functionalities, Java Reflection APIs provides themechanism to retrieve the values from respective fields and accordingly creates the java objects
These objects enable to invoke methods to achieve the desired functionality.
Support toSupport toSupport toSupport to XML parsing:XML parsing:XML parsing:XML parsing: Java has JAXP-APIs to read the xml data and create the xml documentusing different xml parsers like DOM and SAX. These APIs provides mechanism to share data
among different applications over the internet.
Support toSupport toSupport toSupport to Web Services :Web Services :Web Services :Web Services : Java has a rich variety of APIs to use xml technology in diverseapplications that supports N-Tiered Enterprise applications over the internet. Features like JAXB
JAXM, JAX-RPC , JAXR etc enables to implement web services in java applications. It makes java a
most suited internet language.
Support to java enabled Mobile devices:Support to java enabled Mobile devices:Support to java enabled Mobile devices:Support to java enabled Mobile devices: Java programming language is made in such a way sothat it is compatible with mobile devices also. Java language also works with any java enabled
mobile devices that support MIDP 1.0/2.0 including the Symbian OS mobile devices.
7/30/2019 Object Oriented Technic Notes(Unit5)
16/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
16
JJJJavaavaavaava DDDDatabaseatabaseatabaseatabase CCCConnectivity (JDBC)onnectivity (JDBC)onnectivity (JDBC)onnectivity (JDBC) ::::
JDBC is a standard or open application programming interface (API) for accessing a database from
JAVA programs. The JDBC API define interface & classes for writing database application in java by
making database connection.
Features or Advantage of JDBC:Features or Advantage of JDBC:Features or Advantage of JDBC:Features or Advantage of JDBC: Using JDBC you can send SQL and PL/SQL query todatabase. JDBC is a java API for executing SQL statement and support basic SQL functionality
JDBC Architecture :JDBC Architecture :JDBC Architecture :JDBC Architecture : The JDBC API supports both two-tier and three-tier processingmodels for database access.
1. Java code calls JDBC library2. JDBC loads a driver3. Driver talks to a particular database4.
Can have more than one driver -> more than one database
5. Ideal: can change database engines without changing any application codeType of Drivers:Type of Drivers:Type of Drivers:Type of Drivers: Type 1 JDBC DriverType 1 JDBC DriverType 1 JDBC DriverType 1 JDBC Driver
JDBCJDBCJDBCJDBC----ODBC Bridge driverODBC Bridge driverODBC Bridge driverODBC Bridge driver
Type 1 drivers are "bridge" drivers.They use another technology such as
Open Database Connectivity (ODBC) to
communicate with a database. This is
an advantage because ODBC drivers
7/30/2019 Object Oriented Technic Notes(Unit5)
17/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
17
exist for many Relational Database Management System (RDBMS) platforms. Type 1 driver
needs to have the bridge driver installed and configured before JDBC can be used with it
These drivers are also known as JDBC ODBC Bridge Driver.
AdvantageAdvantageAdvantageAdvantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBCdrivers are already available.
DisadvantagesDisadvantagesDisadvantagesDisadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.2. They are the slowest of all driver types.3. The client system requires the ODBC Installation to use the driver.4. Not good for the Web.
TTTType 2 JDBC Driverype 2 JDBC Driverype 2 JDBC Driverype 2 JDBC DriverNativeNativeNativeNative----API/partly Java driverAPI/partly Java driverAPI/partly Java driverAPI/partly Java driver
Type 2 drivers use a native API to communicate with a database system. Java native methods are
used to invoke the API functions that perform database operations.
Type 2 drivers are generally faster than Type 1 drivers.
AdvantageAdvantageAdvantageAdvantage
Better performance than Type 1 since no jdbc to odbc translation isneeded.
DisadvantageDisadvantageDisadvantageDisadvantage
1. Native API must be installed in the Client System and hence type 2drivers cannot be used for the Internet.
2. If we change the Database we have to change the native API as it isspecific to a database.
3. Usually not thread safe.
7/30/2019 Object Oriented Technic Notes(Unit5)
18/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
18
Type 3 JDBC DriverType 3 JDBC DriverType 3 JDBC DriverType 3 JDBC DriverAll Java/NetAll Java/NetAll Java/NetAll Java/Net----protocol driverprotocol driverprotocol driverprotocol driver
These drivers use middleware to communicate with a
server. The server then translates the protocol to DBMS
function calls specific to DBMS. Type 3 JDBC drivers arethe most flexible JDBC solution because they do not
require any native binary code on the client.
AdvantageAdvantageAdvantageAdvantage
1. This driver is server-based, so there is no need forany vendor database library to be present on client
machines.
2. This driver is very flexible allows access to multiple databases using one driver.DisadvantageDisadvantageDisadvantageDisadvantage
It requires another server application to install and maintain. Traversing the record set may take
longer, since the data comes through the backend server.
Type 4 JDBC DriverType 4 JDBC DriverType 4 JDBC DriverType 4 JDBC DriverNativeNativeNativeNative----protocol/allprotocol/allprotocol/allprotocol/all----Java driverJava driverJava driverJava driver
The Type 4 uses java networking libraries to communicate
directly with the database server. They are also written in
100% java and move efficient among all driver types.
AdvantageAdvantageAdvantageAdvantage
1. The major benefit of using a type 4 jdbc drivers are thatthey are completely written in Java to achieve platform independence and eliminatedeployment administration issues. It is most suitable for the web.
DisadvantageDisadvantageDisadvantageDisadvantage
With type 4 drivers, the user needs a different driver for each database.
7/30/2019 Object Oriented Technic Notes(Unit5)
19/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
19
Steps of connectivity a JAVA application to DatabaseSteps of connectivity a JAVA application to DatabaseSteps of connectivity a JAVA application to DatabaseSteps of connectivity a JAVA application to Database::::
Loading Driver Establishing Connection Executing Statements Getting Results Closing Database Connection
1.1.1.1. Loading Driver:Loading Driver:Loading Driver:Loading Driver: In this step of the jdbc connection process, we load the driver class by callingClass.forName(String DriverClassName) with the Driver class name as an argument. Once
loaded, the Driver class creates an instance of itself.
Syntax:Syntax:Syntax:Syntax:
try {
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//Or any other driver
}
catch(ClassNotFoundException e) {
System.out.println( Unable to load the driver class! );
}
2.2.2.2.
Establishing Connection:Establishing Connection:Establishing Connection:Establishing Connection:JDBC URL Syntax: jdbc: :
Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so
the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.
The getConnection(getConnection(getConnection(getConnection(String url, String username, String passwordString url, String username, String passwordString url, String username, String passwordString url, String username, String password)))) is a static method of
DriverManagerDriverManagerDriverManagerDriverManager class. Which return a CCCConnectiononnectiononnectiononnection class object.
Syntax :Syntax :Syntax :Syntax :
try{
Connection con=DriverManager.getConnection("jdbc:odbc:vijayDB",,);}
catch( SQLException e ) {
System.out.println( Couldnt get connection! );
}
7/30/2019 Object Oriented Technic Notes(Unit5)
20/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
20
3. Creating a jdbc Statement object:Creating a jdbc Statement object:Creating a jdbc Statement object:Creating a jdbc Statement object: Once a connection is obtained we can interact with thedatabase. Connection interface defines methods for interacting with the database via the
established connection. To execute SQL statements, you need to instantiate a Statement object
from your connection object by using the createStatement() method.
Syntax:Syntax:Syntax:Syntax:Statement statement = con.createStatement(); //con Connection Object
4. Getting Result:Getting Result:Getting Result:Getting Result: Statement interface defines methods that are used to interact with databasevia the execution of SQL statements. The Statement has following methods for executing SQL
statements: executeQuery(), and executeUpdate()
For a SELECT statement, the method to use is executeQuery() that returnsjava.sql.ResultSet object that holds the fetched data from your select query.
For statements that create or modify tables, the method to use is executeUpdate() thatreturns int that represents the number of rows affected by your query.
ResultSetResultSetResultSetResultSet: provides access to a table of data generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of
data. (employee is table name)
Syntax:Syntax:Syntax:Syntax: ResultSet rs=st.executeQuery("SELECT * FROM employee);
Looping the ResultSLooping the ResultSLooping the ResultSLooping the ResultSet:et:et:et: The next() method is used to successively step through the rows of the
tabular results.
Syntax:Syntax:Syntax:Syntax: rs.next(); // rs instance of ResultSet;
5.5.5.5. ClosingClosingClosingClosing and Commiting Transaction :and Commiting Transaction :and Commiting Transaction :and Commiting Transaction :
After task completion we should commit the transaction and then close the connection.Connection object provide two methods for performing these two tasks.
Syntax:Syntax:Syntax:Syntax:
con.commit(); // con is Connection class Object;
con.close();
7/30/2019 Object Oriented Technic Notes(Unit5)
21/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
21
JAVA applicationJAVA applicationJAVA applicationJAVA application with MS Access Connectivity:with MS Access Connectivity:with MS Access Connectivity:with MS Access Connectivity:
Java ClassJava ClassJava ClassJava Class : JDBCDemo.javaimport java.sql.*;
class JDBCDemo {class JDBCDemo {class JDBCDemo {class JDBCDemo {
public static void main(String [] ar) throws Exception {public static void main(String [] ar) throws Exception {public static void main(String [] ar) throws Exception {public static void main(String [] ar) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:united","","");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select *from Student");
System.out.printf("+--------+--------------+--------+\n");
System.out.printf("|%-8s|%-14s|%-8s|","Roll No","Student Name","Branch");
System.out.printf("\n+--------+--------------+--------+");
while(rs.next()) {
System.out.println();System.out.printf("|%-8s|",rs.getString(1));
System.out.printf("%-14s|",rs.getString(2));
System.out.printf("%-8s|",rs.getString(3));
}
System.out.printf("\n+--------+--------------+--------+\n");
con.close();
} //End Of Main Method} //End Of Main Method} //End Of Main Method} //End Of Main Method
}// End Of JDBCDemo class}// End Of JDBCDemo class}// End Of JDBCDemo class}// End Of JDBCDemo class
MSMSMSMS Access Database :Access Database :Access Database :Access Database : College.mdbDatabase name : College and Table name : Studento
OUTPUTOUTPUTOUTPUTOUTPUT ::::
7/30/2019 Object Oriented Technic Notes(Unit5)
22/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
22
Introduction to APPIntroduction to APPIntroduction to APPIntroduction to APPLETLETLETLET::::
What is an Applet ?What is an Applet ?What is an Applet ?What is an Applet ?
Java applet are compiled java class files that are run on a page within a Web browser. Applet are small java program that are primary used in internet computing. They can be
transported over the internet from one computer to another and run using the Applet Viewer orany web browser that support java.
Types of AppletTypes of AppletTypes of AppletTypes of Applet ::::
Applets are mainly categories into two types :
Local Applet :Local Applet :Local Applet :Local Applet : The applets that are available on a machine and are tested and run on samemachine are called local applets.
Remote Applet :Remote Applet :Remote Applet :Remote Applet : The applets that are available on a machine and are tested and run on remote
machine using its address or URL are called remote applets.
CreatingCreatingCreatingCreating a Simplea Simplea Simplea Simple Applet :Applet :Applet :Applet :
Applet begins with two importimportimportimport statements. The first imports the Abstract Window Toolkit
(AWT) classes. Applets interact with the user through the AWT. The AWT contains support
for a window-based, graphical interface. The second importimportimportimport statement imports the appletappletappletapplet
package, which contains the class AppletAppletAppletApplet. Every applet that you create must be a subclass of
AppletAppletAppletApplet....
7/30/2019 Object Oriented Technic Notes(Unit5)
23/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
23
Developing Simple AppletDeveloping Simple AppletDeveloping Simple AppletDeveloping Simple Applet : FirstApplet.java: FirstApplet.java: FirstApplet.java: FirstApplet.javaimport java.applet.*;
import java.awt.*;
/*
*/
public class FirstApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World..!!!",25,50);
}
}
Compiling and Running Applet :Compiling and Running Applet :Compiling and Running Applet :Compiling and Running Applet :
Compile :Compile :Compile :Compile :
javac FirstApplet.java
Run :Run :Run :Run :
There are two ways in which you can run an applet:
Executing the applet within a Java-compatible Web browser. Using an applet viewer, such as the standard SDK tool, appletviewerappletviewerappletviewerappletviewer. An
applet viewer executes our applet in a window. This is generally the fastest
and easiest way to test our applet.
appletviewer FirstApplet.java
or
appletviewer TestApplet.html
or
Run TestApplet.html page using web browser
7/30/2019 Object Oriented Technic Notes(Unit5)
24/30
7/30/2019 Object Oriented Technic Notes(Unit5)
25/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
25
The Paint Method :The Paint Method :The Paint Method :The Paint Method :Our applet has a method to paint some colored graphics like lines, circles, rectangles etc on the
applet screen.
public void paint(Graphicsgggg) { } public says that anyone can use this method void says that it does not return a result paint is the name of the method
Method names should begin with a lowercase letter The argument, or parameter (theres only one) is inside parentheses that is a reference of
Graphics class of awt package.
A Graphics is an object that holds information about a painting It remembers what color you are using It remembers what font you are using You can paint on it (but it doesnt remember what you have painted)
Methods Of Graphics Class :Methods Of Graphics Class :Methods Of Graphics Class :Methods Of Graphics Class : drawStringdrawStringdrawStringdrawString(String text, int x, int y) drawLinedrawLinedrawLinedrawLine( int startX, int startY, int endX, int endY) drawRectdrawRectdrawRectdrawRect(int top, int left, int width, int height) fillRectfillRectfillRectfillRect(int top, int left, int width, int height)
drawdrawdrawdrawRoundRoundRoundRoundRectRectRectRect(int top, int left, int width, int height,int arcwidth, int archeight) fillfillfillfillRRRRoundoundoundoundRectRectRectRect(int top, int left, int width, int height, int arcwidth, int archeight) drawOvaldrawOvaldrawOvaldrawOval(int top, int left, int width, int height) fillOvalfillOvalfillOvalfillOval(int top, int left, int width, int height) drawdrawdrawdrawArcArcArcArc(int x, int y, int width, int height, int startAngle, int arcAngle) fillArcfillArcfillArcfillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
7/30/2019 Object Oriented Technic Notes(Unit5)
26/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
26
Introduction to SERVLETIntroduction to SERVLETIntroduction to SERVLETIntroduction to SERVLET::::
Servlets are server side Java classes that add functionality to a web server in a manner similarto the way applets add functionality to a browser.
Servlets can be used as a replacement for CGI scripts (or ASP scripts) and they support thestandard request/response protocol supported by web servers.
In this request/response protocol, a client sends a request message to a server and the serverresponds by sending back a reply message
Reply is usually as HTML Could be image, audio stream, video stream, etc.
Servlets classes generally implements either the Servlet interface or extend the HttpServletabstract class
Servlet runs on J2EE servers web container that is servlet container (Tomcat is a popular one)
Servlets are platform independent Servlets are generally invoked from a hyperlink or from the action attribute of an HTML
form.
The Servelt API :The Servelt API :The Servelt API :The Servelt API :Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servletjavax.servletjavax.servletjavax.servlet and javax.servlet.httpjavax.servlet.httpjavax.servlet.httpjavax.servlet.http. they are not included in the Java Software Development
Kit. You must download J2EE web server to obtain their functionality.
7/30/2019 Object Oriented Technic Notes(Unit5)
27/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
27
The Servlet Interface :The Servlet Interface :The Servlet Interface :The Servlet Interface :All servlets must implement the ServletServletServletServlet interface. It declares the init( )init( )init( )init( ), service( )service( )service( )service( ), and
destroy(destroy(destroy(destroy()))) methods that are called by the server during the life cycle of a servlet.
Developing Simple Servlet :Developing Simple Servlet :Developing Simple Servlet :Developing Simple Servlet :STEP 1:STEP 1:STEP 1:STEP 1: Create and compile source code of Servlet : FirstServlet.java
import javax.servlet.*;
public class FirstServlet implements Servlet {public class FirstServlet implements Servlet {public class FirstServlet implements Servlet {public class FirstServlet implements Servlet {
public void init(ServletConfig) {
//Code Here For Initialization
}
public void service(ServletRequest req, ServletResponse res)
throws IOException, ServletExcepion {
PrintWriter out = res.getWriter();
out.println("Hello World!!!");
out.println("
");
out.println("This is my first J2EE Web Application using Servlet.");out.close();
}
7/30/2019 Object Oriented Technic Notes(Unit5)
28/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
28
public void destroy() {
//Code Here That is required when Servlet Object unload from container.
}
public String getServletInfo() {
return "This is my First Servelt";
}
public ServletConfig getServletConfig() {
return null;
}
}//End Of FirstServlet class.}//End Of FirstServlet class.}//End Of FirstServlet class.}//End Of FirstServlet class.
STEP 2:STEP 2:STEP 2:STEP 2: Start Tomcat and Deploy FirstServlet on server.
Open Tomcat configuration window from Program menu and then start tomcat or run
startup.batstartup.batstartup.batstartup.bat from the Tomcat installation directory.
STEP 3:STEP 3:STEP 3:STEP 3: Start Web Browser and request the FirstServlet
Start a Web browser and enter the URL shown here:
http://localhost:8080/MyWebApp/FirstServlet
we can also write 127.0.0.1 in place of localhost.
http://127.0.0.1:8080/ MyWebApp/FirstServlet
7/30/2019 Object Oriented Technic Notes(Unit5)
29/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
29
Servlet Life Cycle:Servlet Life Cycle:Servlet Life Cycle:Servlet Life Cycle:
init()init()init()init() - This method is called when a servlet is first invoked by the servlet container. It could
be used to write code that initializes files or connections to databases.
service()service()service()service() - This method process requests from the client (for example, a hyperlink or form
action). It returns a response (usually HTML) back to the client.
The service() method provides two parameters: ServletRequest and ServletResponse toprovide access to the request object and response object
destroy()destroy()destroy()destroy() - Called just before servlet is destroyed by container to enable programmer to clean
up any resources (e.g. close a db connection).
7/30/2019 Object Oriented Technic Notes(Unit5)
30/30
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar
DifDifDifDifference between Servlet and CGIference between Servlet and CGIference between Servlet and CGIference between Servlet and CGI ::::
S.No.S.No.S.No.S.No. ServletServletServletServlet CGI (Common Gateway Interface)CGI (Common Gateway Interface)CGI (Common Gateway Interface)CGI (Common Gateway Interface)
1 Servlets can link directly to the Web server. CGI cannot directly link to Web server.
2 Servlets can share data among each other. CGI does not provide sharing property.
3 Servlets can perform session tracking and
caching of previous computations.
CGI cannot perform session tracking and
caching of previous computations.
4 Servlets are portable. CGI is not portable.
5 In Servlets, the Java Virtual Machine stays up,
and each request is handled by a lightweight
Java thread.process.
In CGI, each request is handled by a
heavyweight operating system
6 Servlets automatically parse and decode
the HTML form data.
CGI cannot automatically parse and decode
the HTML form data.
7 Servlets can read and set HTTP headers,
handle cookies, tracking sessions.
CGI cannot read and set HTTP headers, handle
cookies, tracking sessions.
8 Servlets is inexpensive than CGI. CGI is more expensive than Servlets.
9 Servlet build with java CGI Build with scripting languages. (like C,
C++, Perl etc)