Java Unit 4 Complete
Java Unit 4 Complete
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.
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.
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
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
An Applet Skeleton
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<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
}
}
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() {
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
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.
• 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:
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)
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
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
(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
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:
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:
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.
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
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.
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.
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.
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.
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.
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.
By closing connection object statement and ResultSet will be closed automatically. The close() method of
used to close the connection.
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
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.
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.
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 –
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.
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.