0% found this document useful (0 votes)
3 views30 pages

Java Unit 4 Complete

The document provides an overview of Java's Abstract Window Toolkit (AWT) for developing GUI applications, detailing its component hierarchy including classes like Component, Container, Window, and Frame. It also explains the MVC architecture, emphasizing the separation of application logic from the user interface, and outlines the lifecycle and functionality of applets in Java. Additionally, it covers graphics, color, and font handling within applets, including methods for drawing shapes and managing visual elements.

Uploaded by

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

Java Unit 4 Complete

The document provides an overview of Java's Abstract Window Toolkit (AWT) for developing GUI applications, detailing its component hierarchy including classes like Component, Container, Window, and Frame. It also explains the MVC architecture, emphasizing the separation of application logic from the user interface, and outlines the lifecycle and functionality of applets in Java. Additionally, it covers graphics, color, and font handling within applets, including methods for drawing shapes and managing visual elements.

Uploaded by

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

PREPARED BY: SHAIK RASOOL, ASST.

PROF, MJCET

UNIT 4
4.1 Abstract Window Tool Kit
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications
in java. The AWT classes are contained in the java.awt package. The AWT defines windows
according to a class hierarchy that adds functionality and specificity with each level.

Component
At the top of the AWT hierarchy is the Component class. Component is an abstract class that
encapsulates all the attributes of a visual component. All user interface elements that are
displayed on the screen and that interact with the user are subclasses of Component. It defines
over a hundred public methods that are responsible for managing events.
Container
The Container class is a subclass of Component. It has additional methods that allow other
Component objects to be nested within it. A container is responsible for laying out, components
that it contains. It does this using various layout managers.

1 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply
implements Container. Panel is the superclass for Applet. A Panel is a window that does not
contain a title bar, menu bar, or border. When you run an applet using an applet viewer, the
applet viewer provides the title and border.
Frame
Frame encapsulates a “window.” It is a subclass of Window and has a title bar, menu bar,
borders, and resizing corners.

4.2 MVC Architecture


Model designs based on MVC architecture follow the MVC design pattern and they separate
the application logic from the user interface when designing software. As the name implies
MVC pattern has three layers, which are:
Model – Represents the business layer of the application
View – Defines the presentation of the application
Controller – Manages the flow of the application

In Java Programming context, the Model consists of simple Java classes, the View displays the
data and the Controller consists of servlets. This separation results in user requests being
processed as follows:
1 The browser on the client sends a request for a page to the controller present on the
server
2 The controller performs the action of invoking the model, thereby, retrieving the data
it needs in response to the request
3 The controller then gives the retrieved data to the view
4 The view is rendered and sent back to the client for the browser to display

2 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Advantages of MVC Architecture in Java


MVC architecture offers a lot of advantages for a programmer when developing applications,
which include:
1 Multiple developers can work with the three layers (Model, View, and Controller)
simultaneously
2 Offers improved scalability, that supplements the ability of the application to grow
3 As components have a low dependency on each other, they are easy to maintain
4 A model can be reused by multiple views which provides reusability of code
5 Adoption of MVC makes an application more expressive and easy to understand
6 Extending and testing of the application becomes easy

4.3 Applets
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
• An applet is a Java class that extends the java.applet.Applet class.
• A main() method is not invoked on an applet, and an applet class will not define main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The security of
an applet is often referred to as sandbox security, comparing the applet to a child playing
in a sandbox with various rules that must be followed.
• Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
The Applet Class
Applet class, which provides the foundation for applets. The Applet class is contained in the
java.applet package. Applet contains several methods that give you detailed control over the
execution of your applet. There are two varieties of applets. The first are those based directly
on the Applet class. These applets use the Abstract Window Toolkit (AWT) to provide the
graphic user interface. The second type of applets are those based on the Swing class JApplet.
Swing applets use the Swing classes to provide the GUI. Swing offers a richer and often easier-
to-use user interface than does the AWT. JApplet inherits Applet, thus all the features of Applet
are also available in JApplet,
There are two ways to use an applet:
1. It is specified in an HTML file using an <applet> tag

3 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

<applet code="MyApplet" width=200 height=60>


</applet>
2. The applet tage can be include inside a java source code using comments
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/

Life Cycle of an Applet


Four methods in the Applet class gives you the framework on which you build any serious
applet −
init − This method is intended for whatever initialization is needed for your applet. It is called
after the param tags inside the applet tag have been processed.
start − This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to other
pages.
stop − This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy − This method is only called when the browser shuts down normally. Because applets
are meant to live on an HTML page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
paint − Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt. The
paint( ) method has one parameter of type Graphics. This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context
is used whenever output to the applet is required.
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

An Applet Skeleton
// An Applet skeleton.
import java.awt.*;
import java.applet.*;

4 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() {
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g) {
// redisplay contents of window
}
}

Applet Display Methods


To output a string to an applet, use drawString( ), which is a member of the Graphics class.
Typically, it is called from within either update( ) or paint( ). It has the following general form:
void drawString(String message, int x, int y)

5 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

To set the background color of an applet’s window, use setBackground( ). To set the foreground
color (the color in which text is shown, for example), use setForeground( ).
These methods are defined by Component, and they have the following general forms:
void setBackground(Color newColor)
void setForeground(Color newColor)
Here, newColor specifies the new color. The class Color defines the constants shown here that
can be used to specify colors:

You can obtain the current settings for the background and foreground colors by calling
getBackground( ) and getForeground( ), respectively. They are also defined by Component and
are shown here:
Color getBackground( )
Color getForeground( )\
Example:
/* A simple applet that sets the foreground and
background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class Sample extends Applet{
String msg;
// set the foreground and background colors.
public void init() {

6 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start() {
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g) {
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}

Repaint
One of the important architectural constraints that have been imposed on an applet is that it
must quickly return control to the AWT run-time system. It cannot create a loop inside paint(
). This would prevent control from passing back to the AWT. Whenever your applet needs to
update the information displayed in its window, it simply calls repaint( ). The repaint( ) method
is defined by the AWT that causes AWT run-time system to execute a call to your applet's
update() method, which in turn calls paint(). The AWT will then execute a call to paint( ) that
will display the stored information. The repaint( ) method has four forms. The simplest version
of repaint( ) is:
void repaint ( )
This causes the entire window to be repainted. Other versions that will cause repaint are:
void repaint(int left, int top, int width, int height)
If your system is slow or busy, update( ) might not be called immediately. If multiple calls have
been made to AWT within a short period of time, then update( ) is not called very frequently.
This can be a problem in many situations in which a consistent update time is necessary. One
solution to this problem is to use the following forms of repaint( ):
void repaint (long maxDelay)
void repaint (long maxDelay, int x, int y, int width, int height)
Here, maxDelay specifies the maximum number of milliseconds that can elapse before update(
) is called. If the time elapses before update( ) can be called, it isn't called. It is possible for a

7 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

method other than paint( ) or update( ) to output to an applet's window. To do so, it must obtain
a graphics context by calling getGraphics( ) and then use this context to output to the window.
For most applications, it is better and easier to route window output through paint( ) and to call
repaint( ) when the contents of the window change.

Passing Parameters to Applets


As just discussed, the APPLET tag in HTML allows you to pass parameters to your applet. To
retrieve a parameter, use the getParameter( ) method. It returns the value of the specified
parameter in the form of a String object

4.4 Working with Graphics


All graphics are drawn relative to a window. This can be the main window of an applet, a child
window of an applet, or a stand-alone application window. A graphics context is encapsulated
by the Graphics class and is obtained in two ways:
1 It is passed to an applet when one of its various methods, such as paint( ) or update( ),
is called.
2 It is returned by the getGraphics( ) method of Component

• Drawing Lines:
Lines are drawn by means of the drawLine( ) method, shown here:
void drawLine(int startX, int startY, int endX, int endY)
• Drawing Rectangles
The drawRect( ) and fillRect( ) methods display an outlined and filled rectangle, respectively.
They are shown here:
void drawRect(int top, int left, int width, int height)
void fillRect(int top, int left, int width, int height)
To draw a rounded rectangle, use drawRoundRect( ) or fillRoundRect( ), both shown here:
void drawRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width, int height, int xDiam, int yDiam)
• Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOval( ). These methods are shown
here:
void drawOval(int top, int left, int width, int height)
void fillOval(int top, int left, int width, int height)
• Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc( ), shown here:

8 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

void drawArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)
• Drawing Polygons
It is possible to draw arbitrarily shaped figures using drawPolygon( ) and fillPolygon( ), shown
here:
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints)

4.5 Working with Color


Java supports color in a portable, device-independent fashion. The AWT color system allows
you to specify any color you want. Color is encapsulated by the Color class. Color defines
several constants (for example, Color.black) to specify a number of common colors. You can
also create your own colors, using one of the color constructors. Three commonly used forms
are shown here:
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)
Setting the Current Graphics Color
By default, graphics objects are drawn in the current foreground color. You can change this
color by calling the Graphics method setColor( ):
void setColor(Color newColor)
Here, newColor specifies the new drawing color.
You can obtain the current color by calling getColor( ), shown here:
Color getColor( )
Example:
Color c= new Color(100, 100, 255);
g.setColor(c);
g.drawLine(0, 0, 100, 100);

4.6 Working with Fonts


The AWT supports multiple type fonts. Fonts have a family name, a logical font name, and a
face name. The family name is the general name of the font, such as Courier. The logical name
specifies a category of font, such as Monospaced. The face name specifies a specific font, such
as Courier Italic. Fonts are encapsulated by the Font class. Several of the methods defined by
Font are

9 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Creating and Selecting a Font


To select a new font, you must first construct a Font object that describes that font. One Font
constructor has this general form:
Font(String fontName, int fontStyle, int pointSize)
fontName specifies the name of the desired font. The style of the font is specified by fontStyle.
It may consist of one or more of these three constants: Font.PLAIN, Font.BOLD, and
Font.ITALIC. To combine styles, OR them together. For example, Font.BOLD | Font.ITALIC
specifies a bold, italics style. The size, in points, of the font is specified by pointSize.

10 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

To use a font that you have created, you must select it using setFont( ), which is defined by
Component. It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font
MVC Architecture

4.7 The Delegation Event Model


The Delegation Event Model defines standard and consistent mechanisms to generate and
process events. In this model, a source generates an event and sends it to one or more listeners.
The listener simply waits until it receives an event. Once an event is received, the listener
processes the event and then returns. A user interface element can “delegate” the processing of
an event to a separate piece of code. In the delegation event model, listeners must register with
a source in order to receive an event notification. This provides an important benefit:
notifications are sent only to listeners that want to receive them
4.7.1 Events
In the delegation model, an event is an object that describes a state change in a source. It can
be generated because of a user interacting with the elements in a graphical user interface.
Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a software
or hardware failure occurs, or an operation is completed
4.7.2 Event Sources
A source is an object that generates an event. Sources may generate more than one type of
event. A source must register listeners to receive notifications about a specific type of event.
Each type of event has its own registration method. Here is the general form:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener( ). The method
that registers a mouse motion listener is called addMouseMotionListener( )
4.7.3 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.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event.
4.7.4 Event Classes
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the
superclass for all events. Its one constructor is shown here:

11 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

EventObject(Object src)
Here, src is the object that generates this event. EventObject contains two methods: getSource(
) and toString( ). The getSource( ) method returns the source of the event. Its general form is
shown here: Object getSource( ) As expected, toString( ) returns the string equivalent of the
event.
The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is
the superclass (either directly or indirectly) of all AWT-based events used by the delegation
event model. Its getID( ) method can be used to determine the type of the event. The signature
of this method is shown here:
int getID( )
Table: List of Few Event classes

i. The ActionEvent Class


The ActionEvent class defines four integer constants that can be used to identify any modifiers
associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and
SHIFT_MASK. In addition, there is an integer constant, ACTION_ PERFORMED, which can
be used to identify action events.
ActionEvent has these three constructors:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
Here, src is a reference to the object that generated this event. The type of the event is specified
by type, and its command string is cmd. The argument modifiers indicates which modifier keys

12 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

(ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. The when
parameter specifies when the event occurred. You can obtain the command name for the
invoking ActionEvent object by using the getActionCommand( ) method, shown here:
String getActionCommand( )
ii. The InputEvent Class

The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for
component input events. Its subclasses are KeyEvent and MouseEvent. InputEvent defines
several integer constants that represent any modifiers, such as the control key being pressed,
that might be associated with the event. Originally, the InputEvent class defined the following
eight values to represent the modifiers:

To test if a modifier was pressed at the time an event is generated, use the isAltDown( ),
isAltGraphDown( ), isControlDown( ), isMetaDown( ), and isShiftDown( ) methods.
iii. The ItemEvent Class
There are two types of item events, which are identified by the following integer constants

In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that signifies


a change of state. ItemEvent has this constructor:
ItemEvent(ItemSelectable src, int type, Object entry, int state)
Here, src is a reference to the component that generated this event.
The getItem( ) method can be used to obtain a reference to the item that generated an event. Its
signature is shown here:
Object getItem( )
The getStateChange( ) method returns the state change (that is, SELECTED or
DESELECTED) for the event. It is shown here:
int getStateChange( )
iv. The KeyEvent Class

13 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

There are many other integer constants that are defined by KeyEvent

The VK constants specify virtual key codes and are independent of any modifiers, such as
control, shift, or alt. KeyEvent is a subclass of InputEvent. Here is one of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Here, src is a reference to the component that generated the event. The type of the event is
specified by type. The system time at which the key was pressed is passed in when. The
modifiers argument indicates which modifiers were pressed when this key event occurred.
The KeyEvent class defines several methods, but the most commonly used ones are
getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns
the key code. Their general forms are shown here:
char getKeyChar( ) int getKeyCode( )
v. The MouseEvent Class
The MouseEvent class defines the following integer constants that can be used to identify them:

MouseEvent is a subclass of InputEvent. Here is one of its constructors:


MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean
triggersPopup)
Here, src is a reference to the component that generated the event. The type of the event is
specified by type. The system time at which the mouse event occurred is passed in when. The
modifiers argument indicates which modifiers were pressed when a mouse event occurred. The
coordinates of the mouse are passed in x and y. The click count is passed in clicks. The
triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.
Two commonly used methods in this class are getX( ) and getY( ). These return the X and
Y coordinates of the mouse within the component when the event occurred. Their forms are
shown here:
int getX( ) int getY( )

14 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Alternatively, you can use the getPoint( ) method to obtain the coordinates of the mouse. It is
shown here:
Point getPoint( )
The getClickCount( ) method obtains the number of mouse clicks for this event.
Its signature is shown here: int getClickCount( )
vi. The TextEvent Class
TextEvent defines the integer constant TEXT_VALUE_CHANGED.
The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event is specified
by type.
vii. The Window Event
The WindowEvent class defines integer constants that can be used to identify them. The
constants and their meanings are shown here:

WindowEvent is a subclass of ComponentEvent. It defines several constructors. The first is


WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is type.
The next three constructors offer more detailed control:
WindowEvent(Window src, int type, Window other) WindowEvent(Window src, int type, int
fromState, int toState) WindowEvent(Window src, int type, Window other, int fromState, int
toState)
Here, other specifies the opposite window when a focus or activation event occurs. The
fromState specifies the prior state of the window, and toState specifies the new state that the
window will have when a window state change occurs. Acommonly used method in this class
is getWindow( ). It returns the Window object that generated the event. Its general form is
shown here:
Window getWindow( )

15 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

4.7.5 Sources of Events


Table : some of the user interface components that can generate the events

4.7.6 Event Listener Interfaces


Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package. When an event occurs, the event source invokes the appropriate
method defined by the listener and provides an event object as its argument.

16 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

i. The ActionListener Interface


This interface defines the actionPerformed( ) method that is invoked when an action event
occurs. Its general form is shown here:
void actionPerformed(ActionEvent ae)
ii. The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes. Its general form is shown here:
void itemStateChanged(ItemEvent ie)
iii. The KeyListener Interface
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are
invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked
when a character has been entered.
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
iv. The MouseListener Interface
This interface defines five methods
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
v. The MouseMotionListener Interface
This interface defines two methods. The mouseDragged( ) method is called multiple times as
the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is
moved. Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
vi. The WindowListener Interface
This interface defines seven methids:
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)

17 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

void windowClosing(WindowEvent we)


void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
4.7.7 Adapter Classes
An adapter class provides an empty implementation of all methods in an event listener
interface. Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface. You can define a new class to
act as an event listener by extending one of the adapter classes and implementing only those
events in which you are interested. For example, the MouseMotionAdapter class has two
methods, mouseDragged( )
and mouseMoved( ), which are the methods defined by the MouseMotionListener interface. If
you were interested in only mouse drag events, then you could simply extend
MouseMotionAdapter and override mouseDragged( ). The empty implementation of
mouseMoved( ) would handle the mouse motion events for you

4.8 AWT Controls


The AWT supports the following types of controls:
• Labels
• Push buttons
• Check boxes
• Choice lists
• Lists
• Scroll bars
• Text editing
These controls are subclasses of Component.
Adding and Removing Controls:
To include a control in a window, you must add it to the window using add() method

18 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Component add(Component compObj)


To remove a control use remove() method
void remove(Component obj)
4.8.1 Labels
A label is an object of type Label, and it contains a string, which it displays. Labels are passive
controls that do not support any interaction with the user.
It has 3 Constructors
Label( ) throws HeadlessException
Label(String str) throws HeadlessException
Label(String str, int how) throws HeadlessException
The first version creates a blank label. The second version creates a label that contains the
string specified by str. This string is left-justified. The third version creates a label that contains
the string specified by str using the alignment specified by how. The value of how must be one
of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER. You can set or change
the text in a label by using the setText( ) method. You can obtain the current label by calling
getText( ). These methods are shown here:
void setText(String str) String getText( )
4.8.2 Buttons
Button defines these two constructors:
Button( ) throws HeadlessException Button(String str) throws HeadlessException
The first version creates an empty button. The second creates a button that contains str as a
label. After a button has been created, you can set its label by calling setLabel( ). You can
retrieve its label by calling getLabel( ). These methods are as follows:
void setLabel(String str) String getLabel( )
Here, str becomes the new label for the button
4.8.3 Using a TextField
The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste
keys, and mouse selections. TextField is a subclass of TextComponent. TextField defines the
following constructors:
TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException

19 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

The first version creates a default text field. The second form creates a text field that is
numChars characters wide. The third form initializes the text field with the string contained in
str. The fourth form initializes a text field and sets its width. TextField (and its superclass
TextComponent) provides several methods that allow you to utilize a text field. To obtain the
string currently contained in the text field, call getText( ). To set the text, call setText( ). These
methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string.

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

The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces
of JDBC API are given below:
1. Driver interface
2. Connection interface
3. Statement interface
4. PreparedStatement interface
5. CallableStatement interface
6. ResultSet interface
7. ResultSetMetaData interface
8. DatabaseMetaData interface
9. RowSet interface

20 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

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


1. DriverManager class
2. Blob class
3. Clob class
4. Types class
4.9.1 Why Should We Use JDBC
• Write once, run anywhere
Multiple client and server platforms.
• Object-relational mapping
Databases optimized for searching/indexing.
Objects optimized for engineering/flexibility.
• Network independence
Works across Internet Protocol.
• Database independence
Java can access any database vendor.
4.9.2 JDBC Structure
JDBC is a SQL-level API. It means that the JDBC allows to construct SQL statements and
embed them inside Java API calls.
The JDBC API is an implementation to interact a database engine. This implementation is
called JDBC Driver.
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.
4.9.3 Types of JDBC Drivers
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
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.

21 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

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.
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:
• 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.

22 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Network Protocol driver:


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

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.
Thin driver:
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.

Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
Disadvantage:
• Drivers depend on the Database.

23 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

4.9.4 JDBC Architectures


JDBC supports two types of processing models for accessing database i.e. two-tier and three-
tier.

1. Two-tier Architecture:
This architecture helps java program or application to directly communicate with the
database. It needs a JDBC driver to communicate with a specific database. Query or
request is sent by the user to the database and results are received back by the user. The
database may be present on the same machine or any remote machine connected via a
network. This approach is called client-server architecture or configuration.
2. Three-tier Architecture:
In this, there is no direct communication. Requests are sent to the middle tier i.e. HTML
browser sends a request to java application which is then further sent to the database.
Database processes the request and sends the result back to the middle tier which then
communicates with the user. It increases the performance and simplifies the application
deployment.
4.9.5 Java Database Connectivity
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection
1) Register the driver class:

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

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundException

24 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's
Jar in the classpath, and then JDBC driver manager can detect and load the driver automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object

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

Syntax of getConnection() method


1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the MySQL

3) Create the Statement object:

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

Syntax of createStatement() method


public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query:

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

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException

25 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object:

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

Syntax of close() method


public void close()throws SQLException
Example to close connection
con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
It avoids explicit connection closing step.
4.9.6 Components of JDBC Architecture
• Driver Manager: It is a class that contains a list of all drivers. When a connection request
is received, it matches the request with the appropriate database driver using a protocol
called communication sub-protocol. The driver that matches is used to establish a
connection.
• Driver: It is an interface which controls the communication with the database server.
DriverManager objects are used to perform communication.
• Connection: It is an interface which contains methods to contact a database.
• Statement: This interface creates an object to submit SQL queries or statements to the
database.
• ResultSet: This contains the results retrieved after the execution of the SQL statements
or queries.
• SQLException: Any errors that occur in database application are handled by this class.

DriverManager class
The DriverManager class acts as an interface between user and drivers. It keeps track of the
drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
Useful methods of DriverManager class

26 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Method Description
1) public static void registerDriver(Driver driver): is used to register the given driver
with DriverManager.
2) public static void deregisterDriver(Driver driver): is used to deregister the given
driver (drop the driver from the
list) with DriverManager.
3) public static Connection getConnection(String url): is used to establish the connection
with the specified url.
4) public static Connection getConnection(String is used to establish the connection
url,String userName,String password): with the specified url, username
and password.

Connection interface:
A Connection is the session between java application and database. The Connection interface
is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection
can be used to get the object of Statement and DatabaseMetaData. The Connection interface
provide many methods for transaction management like commit(), rollback() etc.
By default, connection commits the changes after executing queries.
Commonly used methods of Connection interface:
1) public Statement createStatement():
creates a statement object that can be used to execute SQL queries.

2) public Statement createStatement(int resultSetType,int resultSetConcurrency):


Creates a Statement object that will generate ResultSet objects with the given type and
concurrency.
3) public void setAutoCommit(boolean status):
is used to set the commit status.By default it is true.
4) public void commit():
saves the changes made since the previous commit/rollback permanent.
5) public void rollback():
Drops all changes made since the previous commit/rollback.
6) public void close():
closes the connection and Releases a JDBC resources immediately.

Statement interface:
The Statement interface provides methods to execute queries with the database. The statement
interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.

27 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Commonly used methods of Statement interface:


The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create,
drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple
results.
4) public int[] executeBatch(): is used to execute batch of commands.
ResultSet interface:
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.
By default, ResultSet object can be moved forward only and it is not updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int)
method as well as we can make this object as updatable by:
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.
CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row
next from the current position.
2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.
3) public boolean first(): is used to move the cursor to the first row
in result set object.
4) public boolean last(): is used to move the cursor to the last row
in result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified
row number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative
row number in the ResultSet object, it
may be positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified
column index of the current row as int.
8) public int getInt(String columnName): is used to return the data of specified
column name of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified
column index of the current row as String.
10) public String getString(String is used to return the data of specified
columnName): column name of the current row as String.

28 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

PreparedStatement interface:
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
The performance of the application will be faster if you use PreparedStatement interface
because query is compiled only once.
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given
parameter index.
public void setString(int paramIndex, String value) sets the String value to the given
parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given
parameter index.
public void setDouble(int paramIndex, double value) sets the double value to the given
parameter index.
public int executeUpdate() executes the query. It is used for
create, drop, insert, update, delete
etc.
public ResultSet executeQuery() executes the select query. It returns
an instance of ResultSet.

SQLException Methods:
JDBC Exception handling is very similar to the Java Exception handling but for JDBC, the
most common exception you'll deal with is
java.sql.SQLException
An SQLException can occur both in the driver and the database. When such an exception
occurs, an object of type SQLException will be passed to the catch clause.
The passed SQLException object has the following methods available for retrieving additional
information about the exception –

29 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET


PREPARED BY: SHAIK RASOOL, ASST. PROF, MJCET

Method Description
getErrorCode( ) Gets the error number associated with the exception.
getMessage( ) Gets the JDBC driver's error message for an error,
handled by the driver or gets the Oracle error number and
message for a database error.
getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver
error, no useful information is returned from this method.
For a database error, the five-digit XOPEN SQLstate
code is returned. This method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
printStackTrace( ) Prints the current exception, or throwable, and it's
backtrace to a standard error stream.
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream
you specify.
printStackTrace(PrintWriter w) Prints this throwable and it's backtrace to the print writer
you specify.

4.9.7 Connecting to various Databases

Java Database Connectivity with Oracle

To connect java application with the oracle database, we need to follow 5 following steps. In
this we are using Oracle 10g as the database.
1. Driver class: The driver class for the oracle database
is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the
database, thin is the driver, localhost is the server name on which oracle is running,
we may also use IP address, 1521 is the port number and XE is the Oracle service
name. You may get all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following steps.
• Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database name.
• Username: The default username for the mysql database is root.
• Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.

30 PREPARED BY: SHAIK RASOOL, ASST PROF, MJCET

You might also like