0% found this document useful (0 votes)
62 views1 page

Containers: Create and Compile Servelet Code

The main package for Swing is javax.swing, which must be imported to use Swing components like buttons, labels, and checkboxes. Event handling is important for Swing components that respond to user input, like when a timer goes off. A Swing applet extends JApplet rather than Applet and includes all Applet functionality plus Swing support.

Uploaded by

kasim
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)
62 views1 page

Containers: Create and Compile Servelet Code

The main package for Swing is javax.swing, which must be imported to use Swing components like buttons, labels, and checkboxes. Event handling is important for Swing components that respond to user input, like when a timer goes off. A Swing applet extends JApplet rather than Applet and includes all Applet functionality plus Swing support.

Uploaded by

kasim
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

The main package is javax.swing.

This package must be imported into any program THE SWING PACKAGES
that uses Swing. It contains the classes that implement the basic Swing components, such as
push buttons, labels, and check boxes.

ORIGIN

COMPONENTS ARE LIGHTWEIGHT

KEY FEATURES

SUPPORTS A PLUGGABLE LOOK AND FEEL

The preceding example showed the basic form of a Swing program, but it left out one
important part: event handling. Because JLabel does not take input from the user, it does
not generate events, so no event handling was needed. However, the other Swing components EVENT HANDLING
do respond to user input and the events generated by those interactions need to be handled.
Events can also be generated in ways not directly related to user input. For example, an
event is generated when a timer goes off. Whatever the case, event handling is a large part
of any Swing-based application
The second type of program that commonly uses Swing is the applet. Swing-based applets
are similar to AWT-based applets, but with an important difference: A Swing applet extends SWING APPLET
JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of
the functionality found in Applet and adds support for Swing. JApplet is a top-level Swing
container, which means that it is not derived from JComponent. Because JApplet is a
top-level container, it includes the various panes described earlier. This means that all
components are added to JApplet INTRODUCING SWINGS
PAINTING IN SWING

In general, Swing components are derived from the JComponent class. (The only exceptions
to this are the four top-level containers, described in the next section.) 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.
Thus, a Swing component is built on and compatible with an AWT component.
JAPPLET

JFRAME COMPONENTS

JLIST

JDIALOG

COMPONENTS AND CONTAINERS

JWINDOW

JDIALOG

JFRAME
CONTAINERS

JAPPLET

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

To begin, create a file named HelloServlet.java that contains the following program:
import java.io.;
import javax.servlet.;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response) CREATE AND COMPILE SERVELET CODE
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}

START TOMCAT
Start Tomcat as explained earlier. Tomcat must be running before you try to execute a servlet.

Start a Web Browser and Request the Servlet


Start a web browser and enter the URL shown here:
http://localhost:8080/servlets-examples/servlet/HelloServlet SERVELET EXAMPLE
Alternatively, you may enter the URL shown here:
http://127.0.0.1:8080/servlets-examples/servlet/HelloServlet
This can be done because 127.0.0.1 is defined as the IP address of the local machine. START A WEB BROWSER AND REQUEST THE SERVELET
You will observe the output of the servlet in the browser display area. It will contain the
string Hello! in bold type.
Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when
HTTP GET REQUEST
a form on a web page is submitted. The example contains two files. A web page is defined
in ColorGet.htm, and a servlet is defined in ColorGetServlet.java. The HTML source code
HADNLING HTTP REQUEST AND RESPONSE
for ColorGet.htm is shown in the following listing. It defines a form that contains a select
element and a submit button
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is
defined in ColorPost.htm, and a servlet is defined in ColorPostServlet.java.
The HTML source code for ColorPost.htm is shown in the following listing. It is identical
to ColorGet.htm except that the method parameter for the form tag explicitly specifies that HTTP POST REQUEST
the POST method should be used, and the action parameter for the form tag specifies a BACKGROUND
different servlet.
A session can be created via the getSession( ) method of HttpServletRequest. An
HttpSession object is returned. This object can store a set of bindings that associate names with SESSION TRACKING
objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( )
methods of HttpSession manage these bindings. It is important to note that session state is
shared among all the servlets that are associated with a particular client.
The HTML source code for AddCookie.htm is shown in the following listing. This page USING COOKIES
contains a text field in which a value can be entered. There is also a submit button on the
page.

The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate. The following table summarizes the core interfaces JAVAX.SERVELET PACKAGE SERVELETS
that are provided in this package. The most significant of these is Servlet. All servlets must
implement this interface or extend a class that implements the interface. The ServletRequest
and ServletResponse interfaces are also very important.

Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet and javax.servlet.http. They constitute the Servlet API. Keep in mind that these
packages are not part of the Java core packages. SERVELET API

The javax.servlet.http package contains a number of interfaces and classes that are commonly
used by servlet developers. You will see that its functionality makes it easy to build servlets
that work with HTTP requests and responses. JAVA.SERVELET.HTTP PACKAGE

Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ).
They are implemented by every servlet and are invoked at specific times by the server. Let
us consider a typical user scenario to understand when these methods are called. LIFECYCLE

JTable is a component that displays rows and columns of data. You can drag the cursor
on column boundaries to resize columns.
JTABLE
Depending on its configuration, it is also possible to select a row, column, or cell within the
table, and to change the data within a cell
JTable supplies several constructors. The one used here is
JTable(Object data[ ][ ], Object colHeads[ ])

Atree is a component that presents a hierarchical view of data. The user has the ability to
expand or collapse individual subtrees in this display. Trees are implemented in Swing by
the JTree class. A sampling of its constructors is shown here:
JTree(Object obj[ ])
JTree(Vector<?> v) TREES
JTree(TreeNode tn)

Swing provides a combo box (a combination of a text field and a drop-down list) through
the JComboBox class. A combo box normally displays one entry, but it will also display a
drop-down list that allows a user to select a different entry.
The JComboBox constructor used by
the example is shown here: JCOMBOBOX
JComboBox(Object[ ] items)

In Swing, the basic list class is called JList. It supports the selection of one or more items JLIST
from a list. Although the list often consists of strings, it is possible to create a list of just
about any object that can be displayed

JScrollPane is a lightweight container that automatically handles the scrolling of another


component.
The component to be scrolled is specified by comp. Scroll bars are automatically displayed

when the content of the pane exceeds the dimensions of the viewport.Here are the steps to follow to use a scroll pane: JSCROLLPANE
1. Create the component to be scrolled.
2. Create an instance of JScrollPane, passing to it the object to scroll.
3. Add the scroll pane to the content pane.

JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them JTABBEDPANE
with tabs. Selecting a tab causes the component associated with that tab to come to the
forefront. Tabbed panes are very common in the modern GUI. JTabbedPane defines three constructors. We will use its default constructor, which
creates an empty control with the tabs positioned across the top of the pane. The other two
constructors let you specify the location of the tabs, which can be along any of the four
sides. JTabbedPane uses the SingleSelectionModel model.

JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the
preceding chapter. Here, we will look at JLabel a bit more closely. JLabel can be used to
display text and/or an icon. It is a passive component in that it does not respond to user
input. JLabel defines several constructors. Here are three of them:
JLabel(Icon icon) EXPLORING SWINGS
JLabel(String str)
JLabel(String str, Icon icon, int align)

ImageIcon JLABEL

Icon GetIcon()

String GetText()
The JCheckBox class provides the functionality of a check box. Its immediate superclass is CHECKBOXES
JToggleButton, which provides support for two-state buttons, as just described. JCheckBox
defines several constructors. The one used here is
JCheckBox(String str
Radio buttons are a group of mutually exclusive
RADIO BUTTONS
buttons, in which only one button can be selected at
any one time.
Toggle buttons are objects of the JToggleButton SWING BUTTONS
class. JToggleButton implements AbstractButton.
In addition to creating standard toggle buttons,
JToggleButton is a superclass for two other Swing
components that also represent two-state controls.
These are JCheckBox and JRadioButton, which are JTOGGLEBUTTON
described later in this chapter. Thus, JToggleButton The EventSetDescriptor class represents a Bean event. It supports several methods that
defines the basic functionality of all two-state obtain the methods that a Bean uses to add or remove event listeners, and to otherwise manage Event set descriptor
components. events. For example, to obtain the method used to add listeners, call getAddListenerMethod( ).
To obtain the method used to remove listeners, call getRemoveListenerMethod( ). To obtain
The JButton class provides the functionality of a push button. You have already seen a the type of a listener, call getListenerType( ). You can obtain the name of an event by calling
simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be getName( ).
associated with the push button. Three of its constructors are shown here:
JButton(Icon icon) java is related to c++,which is direct descedant of c.
JButton(String str) JBUTTON The PropertyDescriptor class describes a Bean property. It supports several methods that Property descriptor from c java derives its syntax
JButton(String str, Icon icon) manage and describe properties. For example, you can determine if a property is bound by
calling isBound( ). To determine if a property is constrained, call isConstrained( ). You can histroy and evolution of java *java was concevied by JAMES GOSLING,PATRICK
obtain the name of property by calling getName( ). NAUGHTON,CHRIS WARTH,ED FRANK and MIKE SHERIDAN
at sun microsystem in 1991.
The MethodDescriptor class represents a Bean method. To obtain the name of the method,
Method descriptor *this language was initially was called as "OAK" but was
call getName( ). You can obtain information about the method by calling getMethod( ),
renamed as "JAVA" IN 1995.
shown here:
Method getMethod( ) THE JAVA BEANS API
An object of type Method that describes the method is returned.
Try
The Introspector class provides several static methods that support introspection. Of most
interest is getBeanInfo( ). This method returns a BeanInfo object that can be used to obtain
information about the Bean. The getBeanInfo( ) method has several forms, including the Java exception handling is Catch
one shown here: managed by 5 keywords
exception handling
static BeanInfo getBeanInfo(Class<?> bean) throws IntrospectionException Throw
The returned object contains information about the Bean specified by bean.
Introspector

Finally

Supercl;ass
In the terminology of java a class that is
write once run anywhere paradigm inherited is called "super class"

The properties, events, and methods of a Bean that are exposed to another application
can be controlled
inheritance Subclass
A class that does the inheriting is callled the "Sub class"
The configuration settings of a Bean can be saved in persistent storage and restored
at a later time. In a class hierarchy, when a method in a subclass has the
ADVANTAGES same name and type signature as a method in its superclass,
INTRODUCTION then the method in the subclass is said to override the method
Method overriding in the superclass

A Bean may register to receive events from other objects and can generate events
Nested if statements
that are sent to other objects.
JAVA BEANS If statements

customizers Else if ladder


Selection statement
A Bean developer can provide a customizer that helps another developer configure the Bean

Persistence is the ability to save the current state of a Bean, including the values of a Bean’s Persistence Nested switch statements
properties and instance variables, to nonvolatile storage and to retrieve them at a later time. control statments Switch statements
The object serialization capabilities provided by the Java class libraries are used to provide
persistence for Beans.
For statements
While
Software Development using Java
Iteration Statements Do-while

Int Byte
A simple property has a single value. It can be identified by the following design patterns, Short
Design patterns for simple properties
where N is the name of the property and T is its type:
Integer long
public T getN( )
public void setN(T arg)
INTROSPECTION
design patterns implicitly determine what information is Data types Variables
available to the user of a Bean
Methods and design patterns
Java Language [click to edit]
Complete Reference - Java Float
The BeanInfo interface enables you to explicitly control what
information is available. The BeanInfo interface defines several methods, including these: Float point Double
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( ) One dimensional Array
Using Bean Info Interface
MethodDescriptor[ ] getMethodDescriptors( )

Beans use the delegation event model . Beans can Arrays


generate events and send them to other objects. These can be identified by the following 1) Shreyas Multi dimensional array
design patterns, where T is the type of the event:
public void addTListener(TListener eventListener)
2) Krishna B
public void addTListener(TListener eventListener) Design patterns for events 3) Sanjeev Operator Result
throws java.util.TooManyListenersException 4) Vivek Java provides a rich operator enviraonment.
Multiplication
public void removeTListener(TListener eventListener) most of the operators are divided into following 4 groups
5) kanika / Division
6) Chaitanya % Modulus
Operator Result
Arithmaetic operator ++ Increment
7) Priyanka ~ Bitwise unary NOT
+= Addition assignment
& Bitwise AND
–= Subtraction assignment
| Bitwise OR
*= Multiplication assignment
^ Bitwise exclusive OR
/= Division assignment
Addition Shift right%= Modulus assignment
string builder – Subtraction (also unary minus) – – zero
Shift right Decrement
fill
operators
<< Shift left
additional string methods Bitwise operator Operator Result &= Bitwise AND assignment
== Equal to |= Bitwise OR assignment
data conversition using valueOf() != Not equal to ^= Bitwise exclusive OR
Greater than assignment
searching atrings
< Less than = Shift right assignment
Operator Result
character extraction Relational Operator = Greater than or = Shift right zero fill assignment
& Logical AND
equal to <<= Shift left assignment
| Logical OR
<= Less than or
string concatination with other data types ^ Logical XOR (exclusive OR)
special string operations equal to
|| Short-circuit OR
string literals && Short-circuit AND
STRING HANDLING
string concatination ! Logical unary NOT
Logical Operator &= AND assignment
string conversition and toString() |= OR assignment
^= XOR assignment
The String class supports several constructors. To create an empty String, you call the default constructor. == Equal to
string length
string constructors != Not equal to
string comparision ?: Ternary if-then-else
Simple class
modifying a string Class fundamental
Declaring Object
changing the case of characters within a string

string buffers Assigning Object reference

Methods and classes Adding method to the box class

Constructor
Introducing Methods
This key word

Finalise the methods


Interface can be Extended
One interface can inherit another by use of the keyword Extends

the appendable interface Accessing Implementation through interface References

the comparable interfact Defining an Interface


JAVA LIBRARY An interface is define much like a class.
classloader Implementing Interface
one or more classes can implement that interface
using clone() and the cloneable interface packages and interfaces
Partial Implementation
system

runtime Packages are implicit in the organization


of the standard classes as well as your own program
Understanding packages
process
the URI class Package pkg;
primitive type wrappers
basics Defining a package package My package
exploring java language
void when you are compiling a program that uses
the networking classes and interfaces
the packages,depends on where you have put it
process builder Accessing a package
inet address
object
inet4 address and inet6 address Extension are .jar file stored within the ext directory
class Using Extension
NETWORKING TCP/IP client sockets
math Adding Classes From a Package to Your program
URL
strictmath Access Protection Blocked
URL connection
compiler Running State
HttpURL connection Thread State:Life Cycle of Thread
New State
thread,threadgroup and runnable
cookies Runnable State
threadlocal and inheritable threadl ocal Dead State
TCP/IP server sockets
Blocked on I/O
package
datagrams
Sleeping
runtime permission
sleep()
throwable multithreaded programing Different states implementing
final void wait()
multiple-Threds
security manager Waiting for notification
the applet stub interface
Blocked for joint completion
stacktraceelement applet context and show document
Blocked for lock acquisition
Enum the HTML applet tag

the char sequence interfact requesting and repaintinmg Every java program has one thread,even
if do not create any thread.this thread is called main Thread.
The main Thread implement the runnable interface
two types of applets

applet basics
Creating a thread
extends the thread class,itself
applet architecture
THE APPLET CLASS
an applet skeleton Using Multiple threads in a program

parting thoughts on collections simple applet display methods Using is Alive() and join()

why generic collections? using the status window


Synchronizing Threads
the collection algorithms passing parameters to applets
Communicating Between threads
working with maps the audio clip interface

outputting to the console Suspending and Resuming threads


accessing a collection via an iterator
Window Panes
the collection classes
adapter classes Window and Frame Component
recent changes
two event handling mechanisms Component and Containers
overview
java.util part-1: the collections frame work the delegation event model Creating a Window
the collection interfaces event clases Model-View-Controller Architecture
the random access interface EVENT HANDLING
source of events Destroying
storing user defined classes in collections Initialization
event listener interfaces
comparators Life cycle of the applet
using the deligation event model
Starting
arrays
inner classes applets
the legacy classes and interfaces
Stopping
Painting
Overriding update()
multiline text alignment
The Applet Class
The HTML APPLET Tag
managing text output using fontmatrics

miscellaneous utility classes and interfaces setting the paint mode Including an Applet on a Web Page
Passing Parameters to Applets
formatter working with graphics
Graphical User Interface in Java
timer and timer task AWT classes void close()
Input Stream streaming byte input
random window fundamentals
int Available()
locale working and frame windows mark(int num bytes)
georgian calender INTRODUCTION TO AWT creating a frame window in an applet Byte Stream

date creating a windowed program void write(byte buffer[])


streaming by output void flush()
string tokenizer displaying information within a window
Void close()
java.util part 2:more utility classes IO and File Stream Output stream
bitset Working with colour void write(int b)
int read()
calender Working with fonts Reader streaming character input
abstract void close()
timezone centering text
void mark(int num Chars)
simple time zone
void write(String str)
observable Character Stream Classes
Streaming character output void write(int ch)
currency abstract void close()
file dialogue Writer abstract void flush()
java.utl sub packages dialog boxes viod write(char buffer[]
the resource bundle, list resource bundle and property resource bundle classes using a text field
scanner
managing scroll bars

choice controls

appying check boxes

labels

control fundamentals
Using AWT controls,layout managers and menus
using buttons

checkbox group
using stream i/o
using lists
the console class
using a text area
the byte streams
understanding layout managers
the closable and flushable interfaces
menu bars and menus
the java I/o classes and interfaces handling events by extending AWT components
file input/output :exploring java.io

the stream classes

the character streams

serialization

stream benifits file formats

image fundamentals: creating,loading and displaying

image observer

double buffering

media tracker
images
image consumer

image producer

image filter
remote method invocation
cell animation
regular expresion processing

the core java API packages


NIO,regular expressions and other packages
NIO

reflection

text formatting
using an executor

the concurent API packages


the concurency utilities
using synchronization objects

the concurent collections

the time unit enumeration

locks

atomic operations

You might also like