JAVA Notes
JAVA Notes
What is a Servlet?
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
1. Consider a request for a static web page. A user enters a Uniform Resource Locator (URL)
into a browser.
2. The browser generates an HTTP request to the appropriate web server. The web server
maps this request to a specific file. That file is returned in an HTTP response to the browser.
3. The HTTP header in the response indicates the type of the content. The Multipurpose
Internet Mail Extensions (MIME) are used for this purpose. For example, ordinary ASCII
text has a MIME type of text/plain. The Hypertext Markup Language (HTML) source code of
a web page has a MIME type of text/html.
1
Consider dynamic content. Assume that an online store uses a database to store information
about its business. This would include items for sale, prices, availability, orders, and so forth.
It wishes to make this information accessible to customers via web pages. The contents of
those web pages must be dynamically generated to reflect the latest information in the
database.
In the early days of the Web, a server could dynamically construct a page by creating a
separate process to handle each client request. The process would open connections to one or
more databases in order to obtain the necessary information. It communicated with the web
server via an interface known as the Common Gateway Interface (CGI). CGI allowed the
separate process to read data from the HTTP request and write data to the HTTP response. A
variety of different languages were used to build CGI programs. These included C, C++, and
Perl .However, CGI suffered serious performance problems. It was expensive in terms of
processor and memory resources to create a separate process for each client request. It was
also expensive to open and close database connections for each client request. In addition,the
CGI programs were not platform-independent. Therefore, other techniques were introduced.
Among these are servlets. Servlets offer several advantages in comparison with CGI.
First, performance is significantly better. Servlets execute within the address space of a web
server. It is not necessary to createa separate process to handle each client request.
Second, servlets are platform-independent because they are written in Java.
Third, the Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine.
Finally, the full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI mechanisms
that you have seen already.
2
Static website
Static website is the basic type of website that is easy to create. You don't need the
knowledge of web programming and database design to create a static website. Its web pages
are coded in HTML. The codes are fixed for each page so the information contained in the
page does not change and it looks like a printed page.
Dynamic website
Dynamic website is a collection of dynamic web pages whose content changes dynamically.
It accesses content from a database or Content Management System (CMS). Therefore, when
you alter or update the content of the database, the content of the website is also altered or
updated.Dynamic website uses client-side scripting or server-side scripting, or both to
generate dynamic content.
Client side scripting generates content at the client computer on the basis of user input. The
web browser downloads the web page from the server and processes the code within the page
3
to render information to the user.In server side scripting, the software runs on the server and
processing is completed in the server then plain pages are sent to the user.
Two packages contain the classes and interfaces that are required to build servlets. These are
1. javax.servlet
2. javax.servlet.http
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
4
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access
. information about their environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable
javax.servlet.http Package
The javax.servlet.http package contains a number of interfaces and classes that are commonly
used by servlet developers.
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from
a session.
The following table summarizes the core classes that are provided in this package. The
most important of these is HttpServlet. Servlet developers typically extend this class in
order to process HTTP requests.
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
5
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a
Session value, or that a session attribute changed.
The servlet is invoked when a form on a web page is submitted. The example contains two
ColorGetServlet.java. It defines a form that contains a select element and a submit button.
<html>
<body>
<center>
examples/servlet/ColorGetServlet">
<B>Color:</B>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
6
The doGet( ) method is overridden to process any HTTP GET requests that are sent to this
servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection
that was made by the user.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
The servlet is invoked when a form on a web page is submitted. A web page is defined in
ColorPost.html, and a servlet is defined in the class ColorPostServlet.java. It is identical to
ColorGet.html except that the method parameter for the form tag explicitly specifies that the
POST method should be used, and the action parameter for the form tag specifies a
different servlet.
<html>
<body>
<center>
<form name="Form1"method="post"
action="http://localhost:8080/servletsexamples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
7
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorPostServlet.java is shown in the following listing. The doPost( )
method is overridden to process any HTTP POST requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the selection that was made
by the user. import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
8
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
9
Using Cookies
The servlet is invoked when a form on a web page is submitted. The example contains three
files as summarized here:
File Description
AddCookie.htm Allows a user to specify a value for the cookie named
MyCookie.
AddCookieServlet.java Processes the submission of AddCookie.htm.
GetCookiesServlet.java Displays cookie values.
The HTML source code for AddCookie.html is shown in the following listing. This page
contains a text field in which a value can be entered. There is also a submit button on the
page. When this button is pressed, the value in the text field is sent to AddCookieServlet
via an HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for AddCookieServlet.java is shown in the following listing. It gets the
value of the parameter named “data”. It then creates a Cookie object that has the name
“MyCookie” and contains the value of the “data” parameter. The cookie is then added to
the header of the HTTP response via the addCookie( ) method. A feedback message is then
written to the browser.
10
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException {
The source code for GetCookiesServlet.java is shown in the following listing. It invokes
the getCookies( ) method to read any cookies that are included in the HTTP GET request.
The names and values of these cookies are then written to the HTTP response. Observe that
the getName( ) and getValue( ) methods are called to obtain this information.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
11
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +"; value = " + value);
}
pw.close();
}
}
Session Tracking
1. Session Tracking
2. Session Tracking Techniques
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we need
to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:
12
Why use Session Tracking?
A Date object encapsulating the current date and time is then created.
The setAttribute( ) method is called to bind the name “date” to this object.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
13
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
14
JSP
JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.
15
The Lifecycle of a JSP Page
JSP page is translated into Servlet by the help of JSP translator. The JSP translator is a part of
the web server which is responsible for translating the JSP page into Servlet. After that,
Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all
the processes that happen in Servlet are performed on JSP later like initialization, committing
response to the browser and destroy.
16
JSP Scriptlet tag (Scripting elements)
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are
the scripting elements first.
The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
In this example, we have created two files index.html and welcome.jsp. The index.html file
gets the username from the user and the welcome.jsp file prints the username with the
welcome message.
File: index.html
<html>
17
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.
Syntax :
<%= statement %>
18
2. Example of JSP expression tag that prints current time
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
In this example, we are printing the username using the expression tag. The index.html file
gets the username and sends the request to the welcome.jsp file, which displays the username.
File: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
The JSP declaration tag is used to declare fields and methods.The code written inside the
jsp declaration tag is placed outside the service() method of auto generated servlet.So it
doesn't get memory at each request.
19
Syntax:
<%! field or method declaration %>
The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variables as well as
methods. methods.
The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is placed outside the
_jspService() method. _jspService() method.
In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.
index.jsp
<html>
<body>
<%!
20
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
21
RMI (Remote Method Invocation)
The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.
The RMI provides remote communication between the applications using two
objects stub and skeleton.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:
Stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
Skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does the
following tasks:
22
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
.
1. The application need to locate the remote method
2. It need to provide the communication with the remote objects, and
3. The application need to load the class definitions for the objects.
The RMI application have all these features, so it is called the distributed application.
23
5. Create and start the remote application
6. Create and start the client application
RMI Example
import java.rmi.*;
public interface AddServerIntf extends Remote {
double add(double d1, double d2) throws RemoteException;
}
The second source file, AddServerImpl.java, implements the remote interface. The
implementation of the add( ) method is straightforward. All remote objects must extend
UnicastRemoteObject, which provides functionality that is needed to make objects available
from remote machines.
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject
implements AddServerIntf {
public AddServerImpl() throws RemoteException {
}
24
public double add(double d1, double d2) throws RemoteException {
return d1 + d2;
}
}
The third source file, AddServer.java, contains the main program for the server machine.
Its primary function is to update the RMI registry on that machine. This is done by using the
rebind( ) method of the Naming class (found in java.rmi). That method associates a name
with an object reference. The first argument to the rebind( ) method is a string that names the
server as “AddServer”. Its second argument is a reference to an instance of AddServerImpl.
import java.net.*;
import java.rmi.*;
public class AddServer {
public static void main(String args[]) {
try {
AddServerImpl addServerImpl = new AddServerImpl();
Naming.rebind("AddServer", addServerImpl);
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
The fourth source file, AddClient.java, implements the client side of this distributed
application. AddClient.java requires three command-line arguments. The first is the IP
address or name of the server machine. The second and third arguments are the two numbers
that are to be summed. The application begins by forming a string that follows the URL
syntax. This URL uses the rmi protocol. The string includes the IP address or name of the
server and the string “AddServer”. The program then invokes the lookup( ) method of the
Naming class. This method accepts one argument, the rmi URL, and returns a reference to
an object of type AddServerIntf. All remote method invocations can then be directed to this
object.
25
The program continues by displaying its arguments and then invokes the remote add( )
method. The sum is returned from this method and is then printed.
import java.rmi.*;
public class AddClient {
public static void main(String args[]) {
try {
String addServerURL = "rmi://" + args[0] + "/AddServer";
AddServerIntf addServerIntf =
(AddServerIntf)Naming.lookup(addServerURL);
System.out.println("The first number is: " + args[1]);
double d1 = Double.valueOf(args[1]).doubleValue();
System.out.println("The second number is: " + args[2]);
double d2 = Double.valueOf(args[2]).doubleValue();
System.out.println("The sum is: " + addServerIntf.add(d1, d2));
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
After you enter all the code, use javac to compile the four source files that you created.
Step Two: Generate a Stub
Before you can use the client and server, you must generate the necessary stub. In the context
of RMI, a stub is a Java object that resides on the client machine. Its function is to present the
same interfaces as the remote server. Remote method calls initiated by the client are actually
directed to the stub. The stub works with the other parts of the RMI system to formulate a
request that is sent to the remote machine. A remote method may accept arguments that are
simple types or objects. In the latter case, the object may have references to other objects. All
of this information must be sent to be serialized and sent to the remote machine If a response
must be returned to the client, the process works in reverse. Note that the serialization and
deserialization facilities are also used if objects are returned to a client.
26
To generate a stub, you use a tool called the RMI compiler, which is invoked from the
command line, as shown here:
rmic AddServerImpl
This command generates the file AddServerImpl_Stub.class.
Step Three: Install Files on the Client and Server Machines
Copy AddClient.class, AddServerImpl_Stub.class, and AddServerIntf.class to a directory
on the client machine. Copy AddServerIntf.class, AddServerImpl.class, AddServerImpl_
Stub.class, and AddServer.class to a directory on the server machine
27
public static java.rmi.Remotelookup(java.lang.String) throws It returns the reference of
java.rmi.NotBoundException, java.net.MalformedURLException, the remote object.
java.rmi.RemoteException;
public static void bind(java.lang.String, java.rmi.Remote) throws It binds the remote object
java.rmi.AlreadyBoundException, java.net.MalformedURLException, with the given name.
java.rmi.RemoteException;
public static void unbind(java.lang.String) throws java.rmi.RemoteException, It destroys the remote object
java.rmi.NotBoundException, java.net.MalformedURLException; which is bound with the
given name.
public static void rebind(java.lang.String, java.rmi.Remote) throws It binds the remote object to
java.rmi.RemoteException, java.net.MalformedURLException; the new name.
28
Java Networking
Java Networking is a concept of connecting two or more computing devices together so that
we can share resources.
Java socket programming provides facility to share data between different computing
devices.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
29
3) Port Number
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC.
6) Socket
30
InterfaceAddress (Added byJava SE 6.)
SocketImpl
CookieHandler
JarURLConnection
SocketPermission
CookieManager (Added by Java SE 6.)
MulticastSocket
URI
DatagramPacket
NetPermission
URL
DatagramSocket
NetworkInterface
URLClassLoader
DatagramSocketImpl
PasswordAuthentication
URLConnection
HttpCookie (Added byJava SE 6.)
Proxy
URLDecoder
HttpURLConnection
ProxySelector
URLEncoder
IDN (Added by Java SE 6.)
ResponseCache
URLStreamHandler
Inet4Address
SecureCacheResponse
31
Java Socket Programming
Java Socket programming is used for communication between the applications running on
different JRE. Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients.
The ServerSocket class is designed to be a “listener,” which waits for clients to connect
before doing anything. Thus, ServerSocket is for servers.
The Socket class is for clients. It is designed to connect to server sockets and initiate protocol
exchanges. Because client sockets are the most commonly used by Java applications.The
creation of a Socket object implicitly establishes a connection between the client and server.
There are no methods or constructors that explicitly expose the details of establishing that
connection. Here are two constructors used to create client sockets:
Socket defines several instance methods. For example, a Socket can be examined at any time
for the address and port information associated with it, by use of the following methods:
32
You can gain access to the input and output streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw an
IOException if the socket has been invalidated by a loss of connection.
33
Program example for client and Server Scoket communication
client
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) {
Socket client = null;
BufferedReader br = null;
try {
System.out.println(args[0] + " " + args[1]);
client = new Socket(args[0],Integer.parseInt(args[1]));
} catch (Exception e){}
DataInputStream input = null;
PrintStream output = null;
try {
input = new DataInputStream(client.getInputStream());
output = new PrintStream(client.getOutputStream());
br = new BufferedReader(new
InputStreamReader(System.in));
String str = input.readLine(); //get the prompt from
the server
System.out.println(str);
String filename = br.readLine();
if (filename!=null){
output.println(filename);
}
String data;
while ((data=input.readLine())!=null) {
System.out.println(data);
}
client.close();
} catch (Exception e){
System.out.println(e);
}
}
}
34
Server
import java.net.*;
import java.io.*;
35
Swing
Swing is a set of classes that provides more powerful and flexible GUI components than does
the AWT.
Befor knowing the application of Swing let’s know the drawbacks of AWT,
The AWT defines a basic set of controls, windows, and dialog boxes that support a usable,
but limited graphical interface.One reason for the limited nature of the AWT is that it
translates its various visual componentsinto their corresponding, platform-specific
equivalents, or peers. This means that the lookand feel of a component is defined by the
platform, not by Java. Because the AWT componentsuse native code resources, they are
referred to as heavyweight.
The use of native peers led to several problems.
First, because of variations betweenoperating systems, a component might look, or
even act, differently on different platforms.This potential variability threatened the
overarching philosophy of Java: write once, runanywhere.
Second, the look and feel of each component was fixed (because it is defined bythe
platform) and could not be (easily) changed.
Third, the use of heavyweight componentscaused some frustrating restrictions.
It became apparent that the limitations and restrictions present in the AWT were sufficiently
serious that a better approach was needed.The solution was Swing. Introduced in 1997,
Swing was included as part of the JavaFoundation Classes (JFC).
Swing Features
Swing components are lightweight. This means that they are written entirely in Java and do
not map directly to platform-specific peers. Because lightweight components are rendered
using graphics primitives, they can be transparent, which enables non rectangular shapes.
Thus, lightweight components are more efficient and more flexible. Furthermore, because
lightweight components do not translate into native peers, the look and feel of each
component is determined by Swing, not by the underlying operating system. This means that
each component will work in a consistent manner across all platforms.
36
Swing Supports a Pluggable Look and Feel
Swing supports a pluggable look and feel (PLAF). Because each Swing component is
rendered by Java code rather than by native peers, the look and feel of a component is under
thecontrol of Swing. This fact means that it is possible to separate the look and feel of a
component from the logic of the component, and this is what Swing does.
In other words, it is possible to “plug in” a new look and feel for any given component
without creating any side effects in the code that uses that component. Pluggable look-and-
feels offer several important advantages. It is possible to define a look and feel that is
consistent across all platforms
The MVC architecture is successful because each piece of the design corresponds to an
aspect of a component.
Model corresponds to the state informationassociated with the component. For example, in
the case of a check box, the model containsa field that indicates if the box is checked or
unchecked.
View determines how thecomponent is displayed on the screen, including any aspects of the
view that are affectedbby the current state of the model.
Controller determines how the component reacts to the user. For example, when the user
clicks a check box, the controller reacts by changing the model to reflect the user’s choice
(checked or unchecked). This then results in the view being updated.
By separating a component into a model, a view, and a controller, the specific
implementation of each can be changed without affecting the other two. For instance,
different view implementations can render the same component in different ways without
affecting the model or the controller.
Although the MVC architecture and the principles behind it are conceptually sound,the high
level of separation between the view and the controller is not beneficial for Swing
components. Instead, Swing uses a modified version of MVC that combines the view and
the controller into a single logical entity called the UI delegate. For this reason, Swing’s
approach is called either the Model-Delegate architecture or the Separable Model
architecture.
Therefore, although Swing’s component architecture is based on MVC, it does not use a
classical implementation of it. Swing’s pluggable look and feel is made possible by its
Model-Delegate architecture.Because the view (look) and controller (feel) are separate from
the model, the look and feel can be changed without affecting how the component is used
within a program.
37
Conversely, it is possible to customize the model without affecting the way that
thecomponent appears on the screen or responds to user input.To support the Model-Delegate
architecture, most Swing components contain two objects.
The first represents the Model. The second represents the UI delegate. Models are definedby
interfaces. For example, the model for a button is defined by the ButtonModel interface.UI
delegates are classes that inherit ComponentUI. For example, the UI delegate for a buttonis
ButtonUI. Normally, your programs will not interact directly with the UI delegate.
There are many differences between java awt and swing that are given below.
38
What is JFC ?
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applicatio
Swing components are derived from the JComponent class. JComponent provides
the functionality that is common to all components. For example, JComponent supports the
pluggable look and feel. JComponent inherits the AWT classes Container and Component.
Containers
Swing defines two types of containers.
The first are top-level containers: JFrame, JApplet,JWindow, and JDialog. These
containers do not inherit JComponent. They do, however,inherit the AWT classes
39
Component and Container. Unlike Swing’s other components, which are lightweight, the
top-level containers are heavyweight. This makes the top-level containers a special case in
the Swing component library. As the name implies, a top-level container must be at the top of
a containment hierarchy. Atop-level container is not contained within any other container.
Furthermore, every containment hierarchy must begin with a top-level container. The one
most commonly used for applications is JFrame. The one used for applets is JApplet.
The second type of containers supported by Swing are lightweight containers. Lightweight
containers do inherit JComponent. An example of a lightweight container is JPanel, which
is a general-purpose container. Lightweight containers are often used to organize and manage
groups of related components because a lightweight container can be contained within
another container. Thus, you can use lightweight containers such as JPanel to create
subgroups of related controls that are contained within an outer container.
// Give the frame an initial size. . The setSize( ) method (which is inherited by JFrame from
the AWT class Component) sets the dimensions of the window, which are specified in
pixels. Its general form is shown here: void setSize(int width, int height)
jfrm.setSize(275, 100);
40
// Terminate the program when the user closes the application closing the window causes the
entire application to terminate.the general form of setDefaultCloseOperation( ) is shown
here:void setDefaultCloseOperation(int what)
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the frame on the event dispatching thread. In general, Swing programs are event-
driven. For example, when a user interacts with a component, an event is generated. An event
is passed to the application by calling an event handler defined by the application. However,
the handler is executed on the event dispatching thread provided by Swing and not on the
main thread of the application. Thus, although event handlers are defined by your program,
they are called on a thread that was not created by your program.
To avoid problems, all Swing GUI components must be created and updated from the event
dispatching thread, not the main thread of the application. However, main( ) is executed on
the main thread. Thus, main( ) cannot directly instantiate a SwingDemo object. Instead, it
must create a Runnable object that executes on the event dispatching thread and have this
object create the GUI.
To enable the GUI code to be created on the event dispatching thread, you must use one of
two methods that are defined by the SwingUtilities class. These methods are invokeLater( )
and invokeAndWait( ). They are shown here:
Here, obj is a Runnable object that will have its run( ) method called by the event dispatching
thread. The difference between the two methods is that invokeLater( ) returns immediately,
but invokeAndWait( ) waits until obj.run( ) returns. You can use one of these methods to call
a method that constructs the GUI for your Swing application, or whenever you need to
modify the state of the GUI from code not executed by the event dispatching thread
41
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingDemo();
}
});
}
}
42