Java Web Technonology unit-2

Document Sample
Java Web Technonology unit-2 Powered By Docstoc
					                                                                                                85


                EXTENSIBLE MARKUP LANGUAGE (XML)
BACKGROUND: The eXtensible Markup Language (XML) was derived from an earlier
language called Standard Generalized Markup Language (SGML). SGML’s main purpose was
to define the syntax of markup languages to represent data using tags. Tags consist of text
enclosed between a less-than symbol (<) and a greater-than symbol (>), as in<tag>. Start tags
begin a particular area, such as <start>; end tags define the end of an area. They look the same as
start tags but have a forward slash (/) immediately following the less-than symbol, as in </end>.
SGML also defines attributes for tags, which are values assigned inside of the less-than and
greater-than symbols, such as the src attribute in <img src=”picture.jpg”>. If this looks familiar,
it should; the most famous implementation of an SGML-based language is the original HTML.

      SGML was used to define the Document Type Definition (DTD) for HTML, and it is still
used to write DTDs for XML. The problem with SGML is its allowances for odd syntax, which
makes creating parsers for HTML a difficult problem:
❑ Some start tags specifically disallow end tags, such as the HTML <img>. Including an end
tag
causes an error.
❑ Some start tags have optional or implied end tags, such as the HTML <p>, which assumes a
closing tag when it meets another <p> or several other tags.
❑ Some start tags require end tags, such as the HTML <script>.
❑ Tags can be embedded in any order. For instance, <b>This is a <i> sample </b> string</i> is
okay even though the end tags don’t occur in reverse order of the start tags.
❑ Some attributes require values, such as src in <img src=”picture.jpg” >.
❑ Some attributes don’t require values, such as nowrap in <td nowrap>.
❑ Attribute can be defined with or without quotation marks surrounding them, so
<img      src=”picture.jpg”> and <img src=picture.jpg> are both allowed.

         All these issues make creating SGML language parsers a truly arduous task. The
difficultly of knowing when to apply the rules caused a stagnation in the definition of SGML




JWT
                                                                                               85


languages. This is where XML begins to fit in. XML does away with all the optional syntax of
SGML that caused so many developers heartache early on. In XML, the following rules apply:




❑ Every start tag must have end tag.
❑ An optional shorthand syntax represents both the start and end tags in one. This syntax uses a
forward slash (/) immediately before the greater-than symbol, such as <tag />. An XML parser
interprets this as being equal to <tag></tag>.
❑ Tags must be embedded in an appropriate order, so end tags must mirror start tags, such as
<b>this is a <i>sample</i> string</b>. It helps to think of start and end tags as similar
to open and close parentheses in math: You cannot close the outermost parenthesis without first
closing all the inner ones.
❑ All attributes require values.
❑ All attributes must use quotes around the values.


INTRODUCTION: XML is a markup language developed by World Wide Web Consortium’s
(W3C’s) XML working group in 1996. XML documents contain only data but not formatting
instructions. XML permits us to create markup for any type of information. That is, in XML, we
can create our own tags and syntax for those tags. The extensibility enables us to create our own
new markup languages for mathematical formulas, music, etc. Some XML-based markup
languages are MathML(for mathematics), Voice XML(for speech), SMIL-Synchronous
Multimedia Integration Language (for multimedia presentations). CML-Chemical markup
Language(for Chemistry) and XBRL-eXtensible Business Reporting Language (for financial
data exchange).XML document is highly portable. Processing XML document requires a
software called as XML parser or XML processor. Parser checks the XML document’s syntax
and process XML(SAX). DOM-based parsers builds tree structures containing XML document
for manipulating the data. SAX based parsers process XML documents and generate events for
tags, text, comments, etc. Even Internet Explorer 5.5(IE 5.5) parser (msxml) can parse and
display XML document.
 Advantages of XML



JWT
                                                                                            85


       XML document is human readable and we can edit any XML document in a simple text
         editor
       The XML document is language neutral that is, it can be created and parsed by different
         languages are same languages.
       Every XML document has a tree structure and hence complex data can easily understand
         in simple manner.
       XML files are independent of an Operating System.


Uses
       XML is used to display the meta contents i.e contents of the documents.
       It is useful in exchanging data between the applications.
       The data can be extracted from the database and it can be used more the one application
         and different application can perform different tasks on this data.

STRUCTURE & CREATION OF XML DOCUMENTS

        A XML document ends with the .xml filename extension. Viewing or modifying an
XML document dose not requires special software. Any text editor that supports ASCII/Unicode
characters can open XML documents to view and edit. An important feature of XML is that it is
both human readable and machine readable.

        Today XML is one of the fastest-growing technologies in the world. Its main purpose is
to represent data in a structured way using plain text. In some ways, XML files are not unlike
databases, which also represent structured view of data. Here is an example XML file:

Program: letter.xml

<?xml version="1.0"?>
<letter>
 <contact type="from">
         <name>MD FEROZ</name>
         <address>Shadnagar</address>
         <mobile>9030267533</mobile>
         <flag id="p" />
 </contact>
 <contact type="to">
         <name>MD FASIHUDDIN</name>


JWT
                                                                                               85


          <address>Malakpet</address>
          <mobile>9030267533</mobile>
          <flag id="p" />
  </contact>
  <paragraph>Dear sir,</paragraph>
   <paragraph>
                Hello Sir, How r u ? Tomarrow we have seminar on XML use in today’s
technology.
  </paragraph>
</letter>

       XML document begins with the XML processing instruction <? xml version = “1.0”?>,
which helps Internet Explorer to know that this document is XML, much like the <HTML> tag
indicates an HTML document. Placing space characters before XML declaration is an error.


       Every XML document must contain exactly one root element, which contains every other
XML elements. In the above program, letter is the root element. Other XML Elements such as
contact that contains other elements are called as XML Container Elements. Element inside i.e.,
a container element name, address, mobile, flag are called child elements or children of that
container element. XML elements and attribute names within XML element can be of any length
and may contain letters, digits, underscores, hyphens and periods. However, XML element
names must begin with either a letter or an underscore. Using either a space or a tab in an XML
element name or attribute name is an error. XML element name and attribute names should be
meaningful and in human readable format.

        IE 5.5 places the symbols plus sign (+) an minus sign(-) to container elements in the
output of the above XML document. A minus sign displays container element’s child elements.
Clicking the minus sign, hides container element’s children and replaces the minus sign with a
plus sign clicking the plus sign again displays container element’s children and replaces the plus
sign with a minus sign.

XML NAMES SPACES

       XML Namespace allows to create two different elements by same common name in a
same documents. But, this can result in naming collisions i.e., multiple different elements can
have the same name in one XML document.



JWT
                                                                                            85


For example:
<Subject> Math <Subject>
          &
<Subject> Java and Web Technologies </Subject>

XML element subject to markup a piece of data. However, in the first case, the subject is
something one studies in school, whereas in the second case, the subject is in the field of
Computer Science. But, XML Namespaces provide a means for us to prevent collisions by
differentiating these two subject elements using namespace prefixes as follows:
  <school : subject>
        Math
  </school : subject>

   <computer science : subject>
        Java and Web Technologies
   </computer science : subject>

Both school and Computer Science are namespaces prefixes.


Program-2

<File-Des>
   <text fname=”input.txt”>
       <describe> It’s a text File</describe>
   </text>
   <text fname=”flower.jpg”>
      <describe> It’s an image file</describe>
   </text>
</File-Des>

       XML namespace uses the keyword xmlns to create namespace prefixes and assign the
corresponding URI (Uniform Resource Identifier) that uniquely identifies the namespace. A URI
is a series of characters for differentiating names, for example, the string “Royal Publishers:
book:textInfo” could be a URI for a namespace that contains elements and attributes related to
Professional Publishers.
<directory
xmlns: text=”royal publisher: book:textInfo”
xmlns: image=”royal publisher:book:imageInfo” >
<text: file filename=”department.xml”>
  <text: description>


JWT
                                                                                                   85


       A department name list
   </text: description>
</text: file>
<image: file filename=”logo.gif”>
  <image: description>
       A department name list
   </image: description>
</image: file>
</directory>

VALID AND WELL-FORMED XML DOCUMENTS

       An XML document is called as Valid XML document if there is a Document Type
Definition (DTD) or XML. Schema associated with it and if the document complies with the
DTD or XML Schema. An XML document is called as Well-Formed XML document if it
contains one or more elements, and if there is precisely one element (the root or document
element) for which neither the start tag nor the end tag is inside any other elements, and if all
other tags nest within each other correctly, and if all elements used in the document must either
be predefined in XML DTD or XML Schema.
1. XML Document Type Definitions.
2. XML Schemas

Applications can use DTDs or schemas to perform validity checks on XML documents.

DOCUMENT TYPE DEFINITIONS (DTD)

       The document type definition is used to define the basic building of any xml document. It
is mainly used to specify the various elements types, attributes and their relationship with one
another. Basically DTD is used to specify the set of rules for structuring data in any XML file.

BUILDING BLOCKS OF DTD

   1. ELEMENTS : The basic entity is element to define the tags.
Declaration : The declaration of Element in DTD
<!ELEMENT name_of_element(context)>
Example:
   <!ELEMENT letter(contact) for one occurrence of element
   <!ELEMENT letter(contact+)for minimum one occurrence of element ( use ‘ +’
   operator)
   <!ELEMENT letter(contact*)for zero or more occurrence of element ( use ‘*’ operator)


JWT
                                                                                             85


      <!ELEMENT letter(contact?)for zero or one occurrence of element ( use ‘?’ operator)

   2. ATTRIBUTES : It defines the values of the elements.
Declaration : An attribute is declared as <!ATTLIST>.
syntax:

        <!ATTLIST name_of_element name_of_attribute attribute_type default_value>

name_of_element : Element name (contact / name / address / mobile)
name_of_attribute : Name of the attribute(type in contact element in above example letter.xml)
attribute_type: It can take the following predefined values.
     ENTITY(The value supplied is an entity)
     ENTITIES(The values supplied is more than one entity)
     NMTOKEN(valid XML name should be supplied)
     NMTOKENS(valid XML multiple name should be supplied)
     ID (It is an unique value)
     IDREF(A unique value ID which refers to the other element)
     CDATA(The value is character Data)
     XML(predefined XML value is supplied)

Default_value: It is a default value of a given attribute
    #REQUIED (It specifies that attribute is required)
    #IMPLIED(It specifies that attribute is not required)
    #FIXED(It specifies that value is fixed).
Example <flag type=”TRUE”>
3. PCDATA or Parsed Character Data : It is a data which can be parsed by the parser.It
carries the tags which are nothing but markup elements(such as <name> ,<address> in above
example).i.e It is an entity that can be expanded. I.e. tags are treated as PCDATA.
4. CDADA or Character Data : It is just opposite to PCDATA which cannot be parsed and it
cannot be expanded. I.e tags are not treated as CDATA

TYPES OF DTD

      1.Internal DTD : In an Internal DTD, we enclose the DTD in a <!DOCTYPE> element,
providing the name of the root element of the document (which is letter here in this program) in
the <!DOCTYPE> element.
      <? xml version=”1.0” ?>
        <DOCTYPE DOCUMENT [
      <!ELEMENT letter (contact+,paragraph+) >
      <!ELEMENT contact (name,address,mobile,flag) >


JWT
                                                                                         85


     <!ATTLIST contact type CDATA #REQUIRED>
     <!ELEMENT name (#PCDATA)>
     <!ELEMENT address (#PCDATA)>
     <!ELEMENT mobile (#PCDATA)>
     <!ELEMENT flag (#PCDATA)>
     <!ATTLIST flag id CDATA #REQUIRED >
     <!ELEMENT paragraph (#PCDATA)>
     ]>
<letter>
  <contact type="from">
          <name>MD FEROZ</name>
          <address>Shadnagar</address>
          <mobile>9030267533</mobile>
          <flag id="p" />
          </contact>
  <contact type="to">
          <name>MD FASIHUDDIN</name>
          <address>Malakpet</address>
          <mobile>9030267533</mobile>
          <flag id="p" />
  </contact>
  <paragraph>Dear sir,</paragraph>
   <paragraph>
                Hello Sir, How r u ? Tomarrow we have seminar on XML use in today’s
technology.
  </paragraph>
</letter>

       In the above example, the document type is letter is the root element which consists
the(contact+) and (paragraph+) represents that the occurrence of contact and paragraph is at
least one or more in the document. The other elements name,address,mobile contains
(#PCDATA).




       2.External DTD : In an external DTD, enclose the syntax of XML elements (i.e., the
DTD) in a separate line(like letter.dtd) with an extension.dtd and which contains the
<!ELEMENTS>. We can specify an external DTD in the XML document with the SYSTEM
attributed in the <!DOCTYPE> element.
                        <!DOCTYPE letter SYSTEM “letter.dtd”>

Uses of DTD


JWT
                                                                                                  85


         A DTD provide common mode of data interchange among various independent
            working groups.
         A DTD is used to validate/invalidate data records received from different sources.
         An organization can define a DTD file, basing on which it can be validate/invalidate
            data received by it from different sources.
Limitation of DTD
    DTD is an document_centric, which describes a text document which mismatch with the
       XML defines structure of information.
      Using DTD along with XML increases the complexity, because DTD defines its own
       grammar and syntax.
      DTD always treats the context of text as text or a child element which is not beneficent
       since the text may be in binary format.
2. XML-Schema

       An XML schema is a worldwide consortium (w3c) to describe the structure of an XML
document. The purpose of an XML Schema is to define the legal building blocks of an XML
document which can be used as an alternative approach to XML DTD.The XML schema
language is called XML Schema Definition (XSD).

An XML Schema:

      defines elements that can appear in a document
      defines attributes that can appear in a document
      defines which elements are child elements
      defines the order of child elements
      defines the number of child elements
      defines whether an element is empty or can include text
      defines data types for elements and attributes




                                      Advantages of schema

1) One of the greatest strength of XML Schemas is the support for data types.

      It is easier to validate the correctness of data



JWT
                                                                                            85


      It is easier to work with data from a database
      It is easier to define data patterns (data formats)
      It is easier to convert data between different data types

2) Another great strength about XML Schemas is that they are written in XML.

      You don't have to learn a new language.
      you can use your XML parser to parse your Schema files
      You can manipulate your Schema with the XML DOM
      You can transform your Schema with XSLT

3) XML Schemas Secure Data Communication

       With XML Schemas, the sender can describe the data in a way that the receiver will
understand.

4) XML Schemas are Extensible

       XML Schemas are extensible, because they are written in XML.

                                    XML FILE (note.xml)

<?xml version="1.0"?>
<note>
  <to>Md Feroz Khanani</to>
  <from>Fasiuddin</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

                                     DTD FILE (note.dtd)

<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

                                  SCHEMA FILE (note.xsd)

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
<xs:element name="note">
  <xs:complexType>
   <xs:sequence>
        <xs:element name="to" type="xs:string"/>


JWT
                                                                                            85


         <xs:element name="from" type="xs:string"/>
         <xs:element name="heading" type="xs:string"/>
         <xs:element name="body" type="xs:string"/>
   </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema>

                                        MySchema.xml

<?xml version=”1.0” encoding=”UTF-8”?>
<note xmlns:xsi=”http: http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchameLoaction=”note.xsd”>
 <to>Md Feroz Khanani</to>
  <from>Fasiuddin</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

       The xs is qualifier used to identify the schema elements and types. The document element
of schema is xs:schema. The xs:schema is the root element which takes the attribute xmlns
which has the value http://www.w3.org/2001/XMLSchema. This declaration indicates that
document should follow the rules of XML Schema which is define by the consortium in
2001.The xs:element defines the xml element in the above case to,form,heading and body and
these elements are of simple string types.

Example-2: Create an XML Schema and DTD of a vehicle information such as name, color,
model, price, mileage etc.
                                    vehicle.xml

<?xml version=”1.0” encoding=”UTF-8”?>
<bike>
  <name>splendor</name>
  <color>black</color>
  <model>02K3</model>
  <price>45000</price>
  <mileage>57</mileage>
</bike>

                                             vehicle.dtd

<!ELEMENT bike(name,color,model,price,mileage)>
<!ELEMENT name (#PCDATA)>



JWT
                                                                                        85


<!ELEMENT color (#PCDATA)>
<!ELEMENT model (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ELEMENT mileage (#PCDATA)>

                                     vehicleDTD.xml
<?xml version=”1.0” ? >
<!DOCTYPE bike SYSTEM “vehicle.dtd”>
<bike>
  <name>splendor</name>
  <color>black</color>
  <model>02K3</model>
  <price>45000</price>
  <mileage>57</mileage>
</bike>
                                         vehicle.xsd
<?xml version=”1.0”? >
<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema”>
<xs:element name=”bike”>
  <xs:complexType>
     <xs:sequence>
          <xs:element name="name" type="xs:string"/>
          <xs:element name="color" type="xs:string"/>
          <xs:element name="model" type="xs:string"/>
          <xs:element name="price" type="xs:decimal"/>
          <xs:element name="mileage" type="xs: integer"/>
      </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>
                                     vehicleschema.xml
<?xml version=”1.0” encoding=”UTF-8”?>
<bike xmlns:xsi=”http: http://www.w3.org/2001/XMLSchema-instance"
   xsi:noNamespaceSchameLoaction=”vehicle.xsd”>
   <name>splendor</name>
   <color>black</color>
   <model>02K3</model>
   <price>45000</price>
   <mileage>57</mileage>
</bike>

XML Schema Data Types: The following data types can be used to specify the data types of an
element
        1.     String :The string data type is used to define the element containing
           characters, lines, tabs or white spaces
           e.g: <xs:element name =”student_name” type=xs:string”/>



JWT
                                                                                                85


           2. Date: The date data type is used to specify the date .The format of this date is
              yyyy-mm-dd where yyyy denotes year,mm denotes month and dd denotes day.
              e.g: <xs:element name =”Date_of_birth” type=xs: date”/>
           3. Numeric: The Numeric is used to specify the numeric value either decimal or
              Integer
               e.g: <xs:element name =”price” type=xs:decimal”/>

           4. Boolean: It is used to specify the true or false values.
               e.g: <xs:element name =”flag” type=xs:boolean”/>

XML CSS

       Styling XML Cascading Style sheets:-XML files can be combined with cascading style
sheets, when displayed in a browser the XML file will display just as if it were HTML. Style
sheets are used to control the appearance of the web site and to give all the pages of the web site
the same look and feel. One has to use the classes to apply styles which specify the precise font,
size, color and other properties of display text. Cascading Style sheets provide limited formatting
of XML. You can’t use them to create lists of tables. If you need those more complicated
elements then you should use XSL. If you only need a simple way to view an XML file on the
web, then the best alternative is CSS.

                                           library.xml

<? xml version=”1.0” encoding=”ISO-8859-1”?>
<? xml-stylesheet type=”text/css” href=”library.css”?>
<Catalog>
    <Book>
       <Title> Web Technologies</Title>
       <Author>Md Feroz Khanani</Author>
       <Publication>Royal</Publication>
       <Price>Rs.500</Price>
    </Book>
   <Book>
       <Title> Design Pattern</Title>
       <Author>Md Feroz </Author>
       <Publication>SIM</Publication>
       <Price>Rs.340</Price>
    </Book>
  <Book>
       <Title> Web Services </Title>
       <Author>Md Feroz Khanani</Author>
       <Publication>Khanani</Publication>



JWT
                                                                                      85


       <Price>Rs.430</Price>
   </Book>
</Catalog>

                                       library.css
Catalog
  {
      font-family: arial;
      color: red;
      font-size:16pt
 }
 Book
  {
      font-family: times new roman;
      color: blue;
      font-size:14pt
      display: block;
   }
Title
  {
      font-family: times new roman;
      color: green;
      font-size:12pt
  }
Author
  {
      font-family: georgia;
      color: cyan;
  }
Publication, Price
{
     display: block;
     font-family: arial;
     color: black;
   font-size:10pt;
   margin-left:20pt;
}

DOCUMENT OBJECT MODEL (DOM)

       The Document Object Modeling is a W3C recommendation standard consists set of
programming interfaces for accessing and manipulating structured XML and HTML documents.
DOM is set of platform independent and language neutral application programming interface




JWT
                                                                                                 85


(API) which describes how to access and manipulate the information stored in XML or in HTML
documents.
       DOM is an Application Program Interface for XML documents. The DOM API specifies
the logical structure of XML documents and the ways in which they can be accessed and
manipulated. If you write an application which uses a DOM-compliant XML parser then your
application will function in a certain way. Changing the parser you use for another DOM-
complaint parser, written in different languages, does not affect the operation of your application.
       The DOM API is just a specification. Anyone can write an XML parser in any language.
Though the parsers can be implemented in different ways, all should present the same interface
to other application. DOM-compliant applications include all of the functionality needed to
handle XML document. They can build static document, navigate and search through them, add
new elements, delete elements, and modify the content of existing elements.




Thus XML DOM for
   1. Loading the XML document
   2. accessing the elements of XML document
   3. deleting the elements of XML document
   4. changing the elements of XML document.
                      Example: Loading the XML document using DOM
student.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<student>
   <personal>
      <fname>Md Feroz</fname>
      <sname>Khanani</sname>
                <mobile>9247807690</mobile>
         </personal>
    <rollnum>02661A01214</rollnum>
    <branch>Information Technology</branch>
</student>
                                      student.html
<html>
<head>


JWT
                                                                                              85


<title>Loading the XML Doc.</title>
</head>
<body bgcolor="#CCCCFF">
<script type="text/javascript">
try
{
   xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
  try
   {
     xmlDocument = document.implementation.createDocument("","",null);
   }
   catch(e){alert(e.message)}
}
try
{
  xmlDocument.async=false;
  xmlDocument.load("student.xml");
  document.write("Student XML Document is Loaded successfully :");
 }
 catch(e){alert(e.message)}
</script>
</body>
</html>
Explanation:
       The statement    xmlDocument = new ActiveXObject (“Microsoft.XMLDOM”) create
an empty XML document object as xmlDocument. After getting the document and it is loaded
fully in memory to parse using the script hence we must set xmlDocument.async=false and we
must load the xml file using   xmlDocument.load ("student.xml").

Properties and Methods of DOM

       DOM represents all the elements of the XML document in a hierarchical tree structure.
Each name represents a node. A node that contains other nodes is called a parent node. A parent
node can have many children, but a child node can have only one parent node. The DOM has a
single root node, which contains all other nodes in the document. Each node is an object that has
properties, methods and events. Properties associated with a node include names, values, child
nodes, etc. Methods enable programs to create, delete and append nodes, load XML documents,




JWT
                                                                                                   85


etc. The XML parser exposes these methods as a programmatic library called application
programming interface.
       The Document Object Model (DOM) is a tree-based API for XML. Its main focus
isn’t just to parse XML code, but rather to represent that code using a series of interlinked
objects that can be modified and accessed directly without reparsing the code. Using the DOM,
code is parsed once to create a tree model. After that initial parse, the XML is fully represented
in a DOM model, and the original code is no longer needed. Although the DOM is slower than
SAX and requires more overhead because it creates so many objects, it is the method favored by
Web browsers and JavaScript for its ease of use.
Consider the a simple XML document
<?xml version="1.0" encoding="ISO-8859-1"?>
  <student>
     <personal>
         <fname>Md Feroz</fname>
         <sname>Khanani</sname>
          <mobile>9247807690</mobile>
     </personal>
      <rollnum>02661A01214</rollnum>
      <branch>Information Technology</branch>
   </student>

       The node <student> is a root element and the node <personal> is child node but it
consists of three child nodes such as <fname> <sname> and <mobile> and the nodes
<personal><rollnum><branch> are called sibling because these nodes on the same level.


              Property              Method Type                        Description
nodeName                           String             The name of the node; this is defined
                                                      depending on the type of node.
nodeValue                          String             The value of the node; this is defined
                                                      depending on the type of node.
nodeType                           Number             One of the node type constant values
ownerDocument                      Document           Pointer to the document that this node belongs
                                                      to
firstChild                         Node               Pointer to the first node in the childNodes list
lastChild                          Node               Pointer to the last node in the childNodes list
childNodes                         NodeList           A list of all child nodes
previousSibling                    Node               Pointer to the previous sibling; null if this is
                                                      the sibling
nextSibling                        Node               Pointer to the next sibling; null if this is the
                                                      last sibling


JWT
                                                                                           85


hasChildNodes()                    Boolean        Returns true when childNodes contains one or
                                                  more nodes
Attributes                         NamedNodeMap   Contains Attr objects representing an
                                                  element’s attributes; only used for Element
                                                  nodes
appendChild(node)                  Node           Adds node to the end of childNodes
removeChild(node)                  Node           Removes node from childNodes
replaceChild                       Node           Replaces oldnode in childNodes with
                                                  (newnode, oldnode) newnode.
insertBefore                       Node           Inserts newnode before refnode in (newnode,
                                                  refnode) childNodes
getElementByTagName(name)          Node           Returns the tag name(element name)
setAttribute(attribute_name, new   Node           Setting a new attribute value to a node
value of an attribute)
removeAttribute(attribute_name)    Node           To remove the value of attribute
replaceChild(newNode,currNode)     Node           Replace the current node name by new Node
                                                  name

Program

<html>
<head>
<title>Loading the XML Doc.</title>
</head>
<body bgcolor="#CCCCFF">
<script type="text/javascript">
try
{
   xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
  try
   {
     xmlDocument = document.implementation.createDocument("","",null);
   }
   catch(e){alert(e.message)}
}
try
{
  xmlDocument.async=false;
  xmlDocument.load("student.xml");
  document.write("<font size='5'>");
  document.write("<u>Student XML Document is Loaded successfully :</u>");
  document.write("<br>");




JWT
                                                                                85


  document.write("First Name
:"+xmlDocument.getElementsByTagName("fname")[0].childNodes[0].nodeValue);
  document.write("<br>");

  document.write("Second Name
:"+xmlDocument.getElementsByTagName("sname")[0].childNodes[0].nodeValue);
  document.write("<br>");

  document.write("Mobile
:"+xmlDocument.getElementsByTagName("mobile")[0].childNodes[0].nodeValue);
  document.write("<br>");

  document.write("Roll Number
:"+xmlDocument.getElementsByTagName("rollnum")[0].childNodes[0].nodeValue);
  document.write("<br>");

  document.write("Branch
:"+xmlDocument.getElementsByTagName("branch")[0].childNodes[0].nodeValue);
  document.write("<br>");
 }
 catch(e){alert(e.message)}
</script>
</body>
</html>




       The Methods getElementsByTagName is used to access all the elements that are
specified   with    the   tag    name.     For    example,    getElementsByTagName


JWT
                                                                                               85


("rollnum")[0].childNodes[0].nodeValue) the        rollnum represents the tag name in XML
document, childeNodes[0] represents the first child of the rollnum and the value can be read by
using nodeValue property.
Note: we can also access any xml element using the index value such as
                        document.write(value[0].childNodes[0].nodeValue)



XML PROCESSORS


         The main goal of XML processor is to parse the given XML document. Parsers can be
categorized using four parameters such as validating, non-validating, stream-based, or tree-
based.
         A validating parser uses both an XML file and a DTD to check that the XML is bound to
the rules of the application. If the XML breaks the rules then the parser will create an error and
stop processing the file.
         A Non-validating parsers only use the XML document and are quite content if it well
formed. A well formed document is one which sticks to the general rules for XML such as
having only one top-level element and no overlapping tags.
         Stream-based parsers must read the entire document each time that an operation is
requested and send a message to the controlling application when specific events occur. An
example of stream-based parsers is SAX which is primarily written for use with java programs.
         A tree-based parser builds a static representation of the document which corresponds to
the structure of the original XML. This tree may be updated by adding, removing, or modifying
the nodes at runtime. An example of tree-based parser is DOM.
Java has a rich sources of in-built API’s for parsing the given XML document in two ways.

               Parsing using SAX( A event based approach)
               Parsing using DOM( A tree based approach)




JWT
                                                                                                85




1.SIMPLE API FOR XML (SAX): After XML was defined as a language, the need arose for a
way to both represent and manipulate XML code using common programming languages such as
Java. First came the Simple API for XML (SAX) project for Java. SAX provides an event-based
API to parse XML. Essentially, SAX parsers start out at the beginning of the file and parse their
way through the code in one straight pass, firing events every time it encounters a start tag, end
tag, attribute, text, or other XML syntax. It is up to the developer, then, to determine what to do
when each of these events occurs. SAX parsers are lightweight and fast because they just parse
the text and continue on their way. Their main downside is the inability to stop, go backward, or
access a specific part of the XML structure without starting from the beginning of the file.


A program to check the xml document is well formed or not using SAX parser.


import javax.swing.*;
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class SAX_Parser
{
        public static void main(String[] args)
        {
              try
                {
          String filename = JOptionPane.showInputDialog("Enter The Name of XML
Document!");
                  File fp = new File(filename);
                  if(fp.exists())
                         {
                           try
                                 {
                                   XMLReader reader = XMLReaderFactory.createXMLReader();
                                   reader.parse(filename);
                           JOptionPane.showMessageDialog(null,""+filename+" is Well
Formed:");
                                 }
                                 catch(Exception e)
                                 {



JWT
                                                                                             85


                      JOptionPane.showMessageDialog(null,""+filename+" is Well not
Formed:");
                                     System.exit(1);
                             }
                      }
                      else
                      {
                             System.out.println("File Not present!!!");
                      }
               }
               catch(Exception io){io.printStackTrace();}
        }
}




Explanation:
    The package org.xml.sax.* provides the classes and interfaces for simple API for XML
        (SAX) which is component API of JAVA –API.
       The package org.xml.sax.helper.* provides the helper classes and interfaces for simple
        API for XML (SAX) which is component API of JAVA –API.
       The XMLReaderFactory helps to create an XML reader. This reader parses the xml
        document using the parse() method.




JWT
                                                                                               85


A program to display the contents of XML document using SAX parser

import javax.swing.*;
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class Display_SAX
{
        public static void main(String[] args)
        {
          try
                 {
           String filename = JOptionPane.showInputDialog("Enter The Name of XML
Document!");
                   File fp = new File(filename);
                   if(fp.exists())
                          {
                            try
                                  {
                                    SAXParserFactory spf = SAXParserFactory.newInstance();
                                    SAXParser parser = spf.newSAXParser();
                            System.out.println("XML Elements from the File "+finename+" are....");
                                    DefaultHandler handler = new DefaultHandler();
                                          {
                                          public void startElement(String uri,String localName,
                                          String elements,Attributes attibute) throws SAXException
                                              {
                                                         System.out.println("\t"+elements);
                                              }
                                           };
                                  parser.parse(filename,handler);
                          }
                            catch(Exception e){}
                 }
                  else
                 System.out.println("File Not present!!!");
                 }
        catch(Exception e){}
   }
}

Explanation:

       The SAXParserFactory creates and instance spf, using which the parser object is
created which can be further used to invoke the parser() methods to parse the XML document.



JWT
                                                                                             85


The DefaultHandler is a SAX base class for event handler, the instance of this class handler is
used as second parameter is parse method.The startElement() can be called at the beginning of
every element in the XML document.
uri: denotes the namespace uri.
localName: is the node’s name.
element : qualified name defined in XML specification.
attribute: denotes the default attribute values from XML file




2.DOCUMENT OBJECT MODEL (DOM API) : DOM is a tree based parsing method used to
parse the given XML document, Java provides built-in API’s which consists the method to load
the entire XML document into memory before it starts processing. It is mainly suitable for small
application but not large application since it requires larger amount of memory to store the XML
document.
            A program to check the well formed XML document using DOM API
import javax.xml.parsers.*;
import javax.swing.*;
import java.io.*;
import org.xml.sax.*;
import org.w3c.dom.*;
public class DOM_Parser
{
        public static void main(String[] args)
        {
           try
                {
          String filename = JOptionPane.showInputDialog("Enter The Name of               XML
Document!");
                  File fp = new File(filename);
                  if(fp.exists())
                         {
                           try
                                 {
                           DocumentBuilderFactory                     factory              =
DocumentBuilderFactory.newInstance();
                                   DocumentBuilder builder = factory.newDocumentBuilder();


JWT
                                                                                        85


                                 InputSource ipsrc= new InputSource(filename);
                                 Document doc = builder.parse(ipsrc);
                          JOptionPane.showMessageDialog(null," "+ filename + " is Well
Formed:");
                             }
                             catch(Exception e)
                             {
                      JOptionPane.showMessageDialog(null,""+filename+"     is   Well    not
Formed:");
                                     System.exit(1);
                              }
                      }
                      else
                      {
                              System.out.println("File Not present!!!");
                      }
               }
               catch(Exception io){io.printStackTrace();}
      }
}
Explanation:
      The package javax.xml.parsers.* provides various classes to allow for processing of
XML document. The classes DocumentBuilder and DocumentBuilderFactory define in this
package. The package org.w3c.dom provides classes and interfaces for DOM for processing
XML document.
A program to display the contents of XML document using DOM API
import javax.xml.parsers.*;
import javax.swing.*;
import java.io.*;
import org.xml.sax.*;
import org.w3c.dom.*;
public class DOM_Display_Parser
{
        public static void main(String[] args)
        {
       try
                {
          String filename = JOptionPane.showInputDialog("Enter The Name of             XML
Document!");
                  File fp = new File(filename);
                  if(fp.exists())
                         {




JWT
                                                                                   85


                         DocumentBuilderFactory                      factory     =
DocumentBuilderFactory.newInstance();
                         DocumentBuilder builder = factory.newDocumentBuilder();
                         InputSource ipsrc= new InputSource(filename);
                         Document doc = builder.parse(ipsrc);
                         NodeList list= doc.getElementsByTagName("*");
                         System.out.println("The Elements of "+ filename + "XML
document");
                         for(int i=0;i<list.getLength();i++)
                                    {
                                      Element e = (Element)list.item(i);
                                      System.out.println("\t"+e.getNodeName());
              }
       }
         else {System.out.println("File Not present!!!");}
              }
              catch(Exception io){io.printStackTrace();}
      }
}




Exp
lana
tion
: In
the
abov
e
prog
ram
we have used the DOM methods, getElementsByTagName() to access the element and the
parameter * returns all the elements of XML document. The Method getNodeName() returns
the actual name of the element.

                            Difference between SAX and DOM

                    SAX                                            DOM
1. import javax.xml.parsers.*; import          1. import javax.xml.parser.*;
org.xml.sax.*; import org.xml.sax.helpers.*;   import org.w3c.dom.*;


JWT
                                                                                       85



2. Parsers node by node.                      2. Stores the entire XML document into
                                              memory before processing.
3. Doesn’t store the XML in memory.           3. Occupies more memory.
4. We can’t insert or delete a node.          4. We can insert or delete nodes.
5. Top to bottom traversing.                  5. Traverse in any direction.
6. SAX doesn’t preserve comments.             6.DOM preserves comments
7. SAX parser serves the client application   7. DOM parser always serves the client
always only with pieces of the document.      application with the entire document.




                                       APPLETS
Java supports two types of programs

   1) Application Programs: Application programs are those programs normally created,
       compiled and executed in a local computer. Each application programs contains one




JWT
                                                                                                  85


        main() method. Programs are compiled with javac compiler and executed with java
        interpreter.
   2) Applet Programs: Applet programs are small programs that are priority used in internet
        programming. Applets are downloaded from server and executed at client side using
        compatible “web browser” or “appletviewer”.
        Note: There is no main() method in applet

Applets are divided into two ways:

   a) Local Applet: Applets are created at local system and there is no need of internet
        connection. It simply searches directories in the local system and loads the specified
        applet class.
   b) Remote Applet: Applets are created at remote system by using internet connection. The
        class file is loaded at client side and executed the applet .We must know the URL of
        applet in remote system.
Applet Life Cycle: An Applet is a class defined in java.applet package. When an applet is
loaded, it undergoes a series of changes in its states as follows:
    1) Born (or) initialization---------- init()
   2) Running state -------------------- paint()-start();
   3) Idle state-------------------------- stop();
   4) Dead/destroy--------------------- destroy();


1. Initialization: When an applet enter the initialization state it is loaded by calling init()
method, the applet is born. The initialization variables are placed in this block It is executed only
once in applet life cycle.
Syntax:

      public void init()
               {
                 ________________
                 ________________(Action)
              }




JWT
                                                                                               85


2. Running State: An applet enter the running state when the system calls the start() method of
Applet class. This is executed automatically after the init() method executed . It can call more
than once.
Syntax:
       public void start()
               {
                 ____________
                 ____________(Action)
              }

3. Idle/Stopped State: An applet becomes idle when it is stopped running. This is done by
calling stop() method explicitly.
Syntax:
public void stop()
                {
                     __________
                     __________(Action)
                     __________
                }

4. Dead State: An applet said to be a dead state when it is removed from memory by invoking
destroy() method or when we quit the browser.
Syntax:
public void destroy()
                {
                   ____________
                   ____________(Action)
                   ____________
                 }
5. Display State: This state is useful to display the information on the output screen The paint()
method accomplish this task.
Syntax:
       public void paint(Graphics g)
               {
                  ____________
                  ____________(Display Statements)
                  ____________
               }




JWT
                                                                                    85




                                       Born           init()


                                            start()
                                                      stop()       Idle

                                                        start()

                                      Running
            paint()                                                     destroy()


                                                                    Dead


Steps to write an applet programs

1. Write an applet by extending Applet class and save it (.java file)
2. Compile an executable applet and create .class file.
3. Create an HTML page with the <APPLET> tag
       <APPLET CODE=”AppletName.class” WIDTH=”100” HEIGHT=”200”> </APPLET>
4. Run by typing appletviewer browser
Program:

/*<Applet code=”AppletDemo.class” width=”200” height=”300”></applet>*/
 import java.awt.*;
 import java.applet.Applet.*;
 public class AppletDemo extends Applet
 {
     String msg=” ”;
     public void init()
      {
        msg=msg+”init”;
       }
  public void start()
   {


JWT
                                                                                                 85


        msg=msg+”start”;
   }
 public void paint(Graphics g)
   {
       msg=msg+”paint”;
       g.drawString(msg,50,100);
    }
}

Graphics class: In an applet program, the paint() method consists an arguments of Graphics
class which is defined in java.awt package The Graphics class defines a number of drawing
functions(methods)
                                                Drawling Lines

   1.    drawLine(int start x,int start y,int end x,int end y): It display a line that begins from
         start- x,start- y and end at end- x,end- y.
         Eg: g.drawlLine(10,20,30,40);

                                                 Drawing Rectangles

   1. i) g.drawRect(int x,int y, int w, int h) : It is used to draw rectangles. Where x and y are
         upper left corner of a window and w,h represents the dimension of the rectangle width
         and height respectively.
        ii) g.fillRect() :fill the rectangle.
        iii) draw RoundRect(int top, int left, int width, int height, int xdiam,int ydiam)
        iv) fillRoundRect(int top, int left, int width, int height, int xdiam,int ydiam) where
xdiam and ydiam represents the diameter rounding arc along x and y-axis resp.

                                                Drawing String

   2.    drawstring (“msg”,int x,int y): It is used to display the information in a string message
         starting at x and y points in a window
                                            Ellipse and Circles

   3.    i) void drawOval(int top, int left, int width, int height)
         ii) void fillOval(int top, int left, int width, int height)
         Note: To draw circle the width and height values must be equal
/*<APPLET code="LinesRectsOvals.class" height="250" width="400"></APPLET>*/


JWT
                                                                                                  85


import java.awt.*;
import java.applet.*;
public class LinesRectsOvals extends Applet {
 //display various lines, rectangles and ovals
 public void paint( Graphics g )
   {
                g.drawString("Drawing Grapichs",5,25);
                 g.setColor( Color.red );
                 g.drawLine( 5, 30, 350, 30 );
                 g.setColor( Color.blue );
                 g.drawRect( 5, 40, 90, 55 );
                 g.fillRect( 100, 40, 90, 55 );
                 g.setColor( Color.cyan );
                 g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
                 g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
                 g.setColor( Color.yellow );
                 g.setColor( Color.magenta );
                 g.drawOval( 195, 100, 90, 55 );
                 g.fillOval( 290, 100, 90, 55 );
         }
}




                                          Drawing Arcs

   4.    i) void drawArc(int top, int left, int width, int height, int startAngle, int
        sweepAngle)
         ii) void fillArc(int top, int left, int width, int height, int startAngle, int sweepAngle)

        The top, left Specifies the upper-left corner. Width, height: Specifies the width and
  height of the arc. The arc is drawn from startAngle through an angular distance by
  sweepAngle. Angles are measured in degrees. To draw an arc from 12’0 Clock to 6’0 Clock,
  the start angle is 90 degree and sweep angle 180 degree.


JWT
                                                                                               85



public class DrawingArcs extends Applet
     {
        public void paint(Graphics g)
        {
           g.drawArc(10,40,70,70,0,75);
           g.fillArc(100,40,70,70,0,75);
           g.fillArc(100,100,70,90,0,270);
         }
  }




                                       Drawing Polygons

   5. i) void drawPolygon(int x[],int y[],int sumof points)
      ii) void fillPolygon(int x[],int y[],int sum of points ) - The polygons end points are
specified by the co-ordinate pairs contained within x and y arrays.
import java.awt.*;
import java.applet.*;
public class PolygonExample extends Applet
{
   public void paint(Graphics g)
   {
      int x[]={30,200,30,200,30};
      int y[]={30,30,200,200,30};
      g.drawPolygon(x,y,num);
   }
 }




JWT
                                                                                                 85




Advantages of Applet
   1) Create Animation
   2) Playing sound, video
   3) Drawing Graphics etc…

Disadvantages of Applet: Since the applet is loaded from server to the client machine. It will
corrupt the files on the local machine.


Color class: In AWT, Color class is allows us to create our own color. This class defines
several constants. Such as color.black, color.pink, color.blue, color.gray, color.magneta,
color.green etc. You can also create your own color using color class constructors
                                       Constructors
1. Color c= new Color (int red, int green, int blue) : first constructor takes three integers that
specifies color as a mix of red, green, blue between the range 0-255.
2. Color c= new Color (int rgbvalue) : The second constructor takes a single integer that
contains the mix of red, green, blue. Red-(16to23), green-(8to15), blue-(0to7)
3. Color c= new Color (float red, float green, float blue): The final, third constructor takes
float values in the range of(0.0 to 1.0)
                                             Methods
Color class defines several methods to manipulate colors.
   1) int getRed(), getGreen(): Each of these methods returns the red,green,blue,values from
       the RGB color.
   2) int getRGB(): It returns a packed RGB representation of a color
   3) setColor(color newColor): It is used to set a new color
   4) Color getColor() : This method returns the current used.

Program

 import java.awt.*;
 import java.applet.*;
  public class ColorApplet extends Applet


JWT
                                                                                            85


     {
     public void paint(Graphics g)
      {
        Color c1 = new Color(244,455,100);
        g.setColor(c1);
        g.drawLine(20,40,50,60);
        g.setColor(Color.pink);
        g.drawString(“COLOR APPLET”,50,70);
     }
}

Font class: Java AWT package supports multiple types of fonts .Fonts are used to display
information in a general format.
                                           Constructor
              Font f = new Font (String font-name,int font-style,int font-size)
Font Name: It is the name of the Font family such as “Times New Roman”,” Verdana” etc.
Font-STYLE: It is used to specify the font style such as Font. BOLD,Font. ITALIC and Font.
PLAIN
Font-size: The size in points is specified by font-size.

                                           Methods
1. void setFont(Font object) : It is defined in Component Class used to set the desired Font
created by font object.
2. String[] getAvailabileFontFamilyNames() : This method returns an array of dtringd that
contains of the available font families.
3. Font[] getAllFonts() : This method returns an array of Font objects for all of the available
fonts.
    import java.awt.*;
    import java.applet.*;
    public class FontApplet extends Applet
     {
      public void paint(Graphics g)
       {
         Font f = new Font(“VERDANA”,Font.ITALIC,15);
         g.setColor(Color.pink);
         g.drawString(“THIS TEXT IS DISPLAYED IN VARDANA FONT ,50,70);
    }
}




JWT
                                                                                           85


Frame class: Frame is subclass of window class to create a Window which has title bar, menu
bar, border and resizing corners.
                                      Constructors
1.Frame f1 = new Frame():creates a window frame that doesn’t contains title.
2. Frame f2 = new Frame(“String title”) : It creates a Frame window that contains Title.
                                    Methods
1.void setSize(int WIDTH, int HEIGHT) : It is used to set the Dimension to the created
window. The arguments WIDTH and HEIGHT specifies the width and height of the window.
                                    e.g : f.setSize(200,300);
2 .Dimension getSize() : It returns the dimensions as a width and height of the window
                                    e.g : Dimension = f1.getSize();
3. void setVisible(Boolean value) : A Frame Window which is created and it is not visible by
default. we must call explicitly this method by passing true parameters as an arguments to
visible the Frame. e.g.: f.setVisible(true)
4.void SetTitle(String title) :This method is used to set the Title of the Frame Window
                            e.g : f.setTitle(“Feroz”);
import java.awt.*;
public class FrameDemo extends Frame
  {
     public FrameDemo()
     {
        setTitle(“A Frame Window”);
        Frame f = new Frame();
        setBackground(Color.green);
     }
public void paint(Graphics g)
   {
       g.drawString(“A Frame window “,20,30);
   }
public static void main(String args[])
   {
      FrameDemo fd = new FrameDemo();
      fd.setSize(200,200);
      fd.setVisible(true);
  }
}

ABSTRACT WINDOW TOOL KIT (AWT) : Abstract Window Tool Kit (AWT) is
one of the largest packages in java which is logically organized in hierarchical fashion. AWT



JWT
                                                                                             85


package provides many AWT classes such as AWTEvent, Border Layouts, Graphics class, Font
class, Color class, many AWT controls(Buttons,TextFields,Labels etc). These classes are used to
design a Graphical User Interface (GUI) applications. AWT controls are heavy weight
components and they are not much look-n-feel application.

                                    Component



                                       Container



                              Panel         Window                 MenuContainer


                              Applet                Frame

AWT defines Windows according to a class hierarchy (above) that adds functionality and
specify with each level. The two most common windows are derived from Panel which is used
by the Applet. Much of these functionality are derived from its parent classes.
Component: Component is top most class in a AWT hierarchy. It is an abstract class that
encapsulates all the GUI components displayed on the screen. User interacts with each
components which are responsible for creating Events such as Action Event, Mouse Events, Key
Event etc. Components includes Labels, Button, Text Field, Choice, Checkbox etc.
Container: A Container is a sub class of Component class. It has method called add(Component
obj) to add the components in a container. It is responsible for setting the Layouts (Flow
Layouts, Border Layouts etc) and positioning each components in it using Layout Managers.
Panel: Panel is a concrete sub class of Container. It is just like a container to add a GUI
components using LayoutManagers.We can create multiple Panels object and each panel is then
nested in to a container at last. We can also resize or setSize the panel window. Panel is super
class of Applet class.
Window: Window class creates a top level window. It sits directly on the desktop, we cannot
create window directly but we can implement by using Frames.
Canvas: It is not a part of hierarchy for Applet/Frame windows. These is different valuables
windows upon which you can draw graphs, sheets, pie-charts etc.


JWT
                                                                                                85



AWT controls (or) Components

       Abstract Window Tool Kit is abbreviated as AWT define in the package called java.awt.
This package is used to create Graphical user Interface programs using controls or components.
Controls are the components that allow a user to interact with the application in different ways.
A layout Manages are automatically positions the controls (Components) in a container. The
AWT supports the following types of Controls.
1.Labels 2.Buttons 3.Checkbox 4.CheckboxGroup 5.Choice 6.List 7.Scrollbars
8.TextArea 9.TextField

Adding Controls: -- First create the instance the instance of controls and then add the controls in
a container using the method called add( )

Syntax: add (Component Object)

Removing the Controls: - A control can be removed from the window when it no longer needed
by using a method called remove ( ).

Syntax: void remove (Component Object) : Remove the control form the window.
Syntax: void removeAll (Component Object): Remove all controls from the window

1. Label: Label is text information that display on the GUI as a String. It doesn’t support any
interaction with the user.
                                           Constructors
Label lab1 = new Label() //empty label
Label lab2 = new Label(String str)//String name
Label lab3 = new Label(String str,int how) : This constructor how specify the alignment of
the Label such as Label.LEFT, Label.RIGHT, Label.CENTER.
                                             Methods

1.void setText(String str) : To change the text of the label.
2.String getText( ) : It returns the text name of label.
3.void setAlignment(int how) : It is used to specify the alignment of the label.
4.int getAlignment( ) : It return the alignment of the label.


2. Button: The Button is a component that contains a label and generates an event when a user

JWT
                                                                                                 85


interacts with it.
                                            Constructors
Button b1 = Button ( ) //empty button
Button b2 = Button (String str) //button with string label i.e button name
                                               Methods

1. void setLabel(String str) :It is used to set the label of the Button by str.
2. String getLabel( ) : It return the Label of Button.
                                         Handling Buttons

ActionEvent class : An ActionEvent is generated when Button is clicked/pressed.

                                               Methods

1. Object getSource( ): It return the object on which event occurred.
2. String getActionCommand( ): It returns the command String associated with this action.
                                     ActionListener Interface

Whenever the button is pressed an action event is generated, this event is sent to listener which
implements the ActionListener interface. Which defines a single method                      called
actionPerformed(ActionEvent ae).

3. TextField: The TextField class is a single line text area. It is used to edit the string
information. It is subclass of TextComponent.
                                            Constructors

TextField tf1 = new TextField( ) //empty text field
TextField tf2 = new TextField( int num ) //create the text field num of characters
TextField tf3 = new TextField(String str, int num ) // text field with String value and num of
characters.
TextField tf4 = new TextField(String str ) //create the text field with String

                                               Methods

1.String getText( ) :- It return the information currently in the textfield.
2.void setText(String str ) :- It is used to set the string information in the textfield.
3.String getSelectedText() :- It return the currently selected text.
4.setEditable(Boolean b) :- If b=true the text field can be editable otherwise the text field is not


JWT
                                                                       85


editable.
A program demonstrate the Label, TextField and Button class controls

//<applet code="Factorial.class" width="350" height="200"></applet>
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.applet.*;
public class Factorial extends Applet implements ActionListener
{
  Label label1,label2,label3;
  TextField input,result;
  Button compute;
   public Factorial()
     {
        label1 = new Label("Enter The Number :");
        input = new TextField(15);
        label2 = new Label("Result :");
        result = new TextField(15);
        compute = new Button("Compute");
        compute.addActionListener(this);
        Panel p = new Panel();
        p.add(label1);
        p.add(input);
        p.add(label2);
        p.add(result);
        p.add(compute);
        add(p,BorderLayout.NORTH);
  }
public void actionPerformed(ActionEvent ae)
  {
    int fact=1;
    if(ae.getSource()==compute)
       {
          double num = Integer.parseInt(input.getText());
          for(int i=1;i<=num;i++)
           {
                  fact = fact*i;
           }
      }
        result.setText(""+fact);
  }
}




JWT
                                                                                               85




4. Checkbox: A checkbox is a control that consist a small box that either contains on or off.
There is a label associated with each checkbox control. We can change the state of the checkbox
by clicking on it.
                                           Constructors

Checkbox cb1 = new Checkbox( ): Creates the checkbox with empty label and the state is
unchecked
Checkbox cb2 = new Checkbox( String str) : Creates checkbox with label and state is
unchecked.
Checkbox cb3 = new Checkbox( String str, boolean on/off): Creates the checkbox with label
and checked if the Boolean value is true otherwise unchecked(for false).

                                              Methods

1. Boolean getState( ) :- determines whether the checkbox is checked or not? It return true if it
is checked otherwise it return false.
2. Void setState( Boolean on) :- set the states of checkbox to either checked or unchecked .
3. String getLabel ( ):- Get the checkbox with label name as string.
4. Void setlabel(String str) :- It set the label to the checkbox.

                                   Handling CheckBox Events

ItemEvent Class : An ItemEvent is generated when a checkbox or list item is clicked or
checkable menu item is selected or deselected.
                                              Methods




JWT
                                                                                                85


1. Object getItem( ) : returns the item effected by the event.
2. int getStateChange( ) : returns the type of the state change


ItemListener Interface: Each item is selected or deselected an item event is generated. This
event is sent to the listener. Each listener implements the ItemListener interface. Which defines a
method called itemStateChanged(ItemEvent ie )
//program that demonstrate checkbox and its event handling

import java.awt.*;
import java.awt.event.*;
class CheckBoxEvents extends Frame implements ItemListener
{
    String msg = "";
    Checkbox c1,c2,c3;
    CheckBoxEvents()
     {
        setLayout(new FlowLayout());
        c1 = new Checkbox("CSIT");
        c2 = new Checkbox("CSE");
        c3 = new Checkbox("ECE",true);
        add(c1);
        add(c2);
        add(c3);
        c1.addItemListener(this);
        c2.addItemListener(this);
        c3.addItemListener(this);
        setSize(400,400);
        setVisible(true);
    }
public void itemStateChanged(ItemEvent ie)
   {
       repaint();
   }
public void paint(Graphics g)
  {
     msg = "State:";
     g.drawString(msg,50,150);
     msg="CSIT :-"+c1.getState();
     g.drawString(msg,50,170);
     msg="CSE :-"+c2.getState();
     g.drawString(msg,50,190);
     msg="ECE :-"+c3.getState();
     g.drawString(msg,50,210);



JWT
                                                                                                 85


   }
public static void main(String[] args)
{
      CheckBoxEvents ce = new CheckBoxEvents();
//for closing window
   ce.addWindowListener( new WindowAdapter() {
   public void windowClosing( WindowEvent event )
{ System.exit( 0 ); }
} // end anonymous inner class
); // end
}
}




5. Choice Control: The Choice Control is used to create a pop-up list of items from which
the user may choose. It is a form of Menu Control.
                                           Constructor

                                Choice ch = new Choice ( )

                                           Methods
1. void add(String name) :- It is used to add a selection of list specified by name.
2. String getSelectedItem( ) :-It returns the string of selected item from the choice control.
3. int getSelectedIndex( ) :-It returns the Index of Selected Item.
4. int getItemCount( ) :- It return the total number of item in the list.
5. void select(int index) :-It is used to select the item upon index of item.
6. void select(String name) :- It is used to select the item upon name of the item.
7. String getItem( int index) : - It return the name of the item that contains the value of index.

Handling the Choice Control Event : same as checkbox control.


JWT
                                                                 85



//A program that demonstrate the choice control
import java.awt.*;
import java.awt.event.*;
class ChoiceControlsDemo extends Frame implements ItemListener
{
String msg="";
Choice ch;
public ChoiceControlsDemo()
{
ch= new Choice();
ch.add("CSIT");
ch.add("CSE");
ch.add("ECE");
add(ch);
ch.addItemListener(this);

}
public void itemStateChanged(ItemEvent ie)
   {
       repaint();
      }
public void paint(Graphics g)
    {
msg = ch.getSelectedItem();
if(msg.equals("CSIT"))
setBackground(Color.GREEN);
else if(msg.equals("CSE"))
setBackground(Color.RED);
else if(msg.equals("ECE"))
setBackground(Color.BLUE);
g.drawString("Selection :"+ msg,50,250);
  }
public static void main(String[] args)
   {
      ChoiceControlsDemo choice = new ChoiceControlsDemo();
      choice.setSize(200,200);
      choice.setVisible(true);
   }
}




JWT
                                                                                           85




6. CheckboxGroup: These CheckboxGroup is also called radio buttons. This class is used
to select one choice at any time. It is a collection of Checkbox. It can be created by using a
Checkbox constructor by passing the Object of CheckboxGroup. It generates the ItemEvent
which listen by ItemLisener interface.
//program that demonstrate the checkboxgroup with Event
import java.awt.*;
import java.awt.event.*;
class CheckBoxGroup extends Frame implements ItemListener
{
String msg = "";
Checkbox c1,c2,c3;
CheckboxGroup cbg;
CheckBoxGroup()
  {
setLayout(new FlowLayout());
cbg = new CheckboxGroup();
c1 = new Checkbox("CSIT",cbg,true);
c2 = new Checkbox("CSE",cbg,false);
c3 = new Checkbox("ECE",cbg,true);
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
setSize(400,400);
setVisible(true);
  }
public void itemStateChanged(ItemEvent ie)
{
try


JWT
                                                                                                   85


{
 repaint();
}
catch(Exception e){e.printStackTrace();}
}
public void paint(Graphics g)
   {
msg = cbg.getSelectedCheckbox().getLabel();
if(msg.equals("CSIT"))
setBackground(Color.RED);
else if(msg.equals("CSE"))
setBackground(Color.GREEN);
else if(msg.equals("ECE"))
setBackground(Color.BLUE);
 }
public static void main(String[] args)
{
     CheckBoxGroup checkboxgroup = new CheckBoxGroup();
}
}




7. List Control : List class provides a multiple choice list of item with scroll bars. List control
generates an ActionEvent Which Must implement ActionListener.
                                           Constructors
1. List l1 = new List( )
2. List l2 = new List( int nrows)
3. List l2 = new List( int nrows, boolean select)
     The first constructor creates a List control that allows only one item in a list will be selected
at once. In second constructor creates a list with number of entries in the list will always visible.
The Third constructor creates a List control that allows multiple items in a list will be selected
whenever the boolean value is true.


JWT
                                                                                            85


                                             Methods

1. void add(String name) :- It is used to add the Item the list control.
2.String getSelectedItem( ):- returns the currently selected item as a string.
3.String getItem(int index ) :- It return the item as a string associated to index value.
4.int getItemCount( ) :- It returns total number of items in a list.

// program that demonstrate List & ActionEvent

import java.awt.*;
import java.awt.event.*;
class ListControl extends Frame implements ActionListener
{
String msg="";
List list;
public ListControl()
{
list = new List(5);
list.add("CSIT");
list.add("CSE");
list.add("ECE");
list.add("EEE");
list.add("MECH");
list.select(3);
add(list);
list.addActionListener(this);
add(list,BorderLayout.NORTH);
setSize(200,200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
repaint();
}
public void paint(Graphics g)
{
msg ="Selected Branch";
msg=msg+list.getSelectedItem();
g.drawString(msg,50,250);
}
public static void main(String[] args)
{
ListControl list = new ListControl();
//for closing window
list.addWindowListener(
new WindowAdapter() {



JWT
                                                                                               85


public void windowClosing( WindowEvent event )
{
System.exit( 0 );
}
} // end anonymous inner class
); // end
}
}




8 .Scroll Bars : scroll bars are used to select continuous values between a specified minimum
and maximum. Scroll bar is oriented horizontally or vertically.
                                            Constructor
1.Scrollbar scroll = new Scrollbar( )
2.Scrollbar scroll = new Scrollbar( int style)
3.Scrollbar scroll = new Scrollbar(int style, int initvalue,int size, int min,int max )
The first constructor creates a vertical scroll bar. The second constructor scroll bar where style
represents the orientation ie.Scrollbar.VERTICALLY or Scrollbar. HORIZONTALLY. In
Third form initvalue=initial value, size=number of units, min=minimum, max=maximum.
                                               Methods
1. void setValues(int style, int initvalue,int size, int min,int max )
2. int getValue( ) :-return the current setting of scrollbar.
3. int getMaximim( ) :-It returns the maximum value of the scroll bar.



JWT
                                                                                                  85


4. int getMinimum( ) :-It returns the minimum value of the scroll bar.

//program to demonstrate scrollbar
import java.awt.event.*;
import java.awt.*;
class ScrollBarDemo extends Frame
{
public ScrollBarDemo()
{
//Scrollbar sv= new Scrollbar();//vertical
Scrollbar sh= new Scrollbar(Scrollbar.VERTICAL);
Panel p = new Panel();
p.add(sh);
add(p);
//Scrollbar ss= new Scrollbar(Scrollbar.HORIZONTAL,1,2,3,5);
}
public static void main(String[] args)
{
ScrollBarDemo scroll = new ScrollBarDemo();
scroll.setSize(200,200);
scroll.setVisible(true);
scroll.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent event )
{
System.exit( 0 );
}
} // end anonymous inner class
); // end
 }
}

9.TextArea control : This control provides the multiline editing text field.It generates the
ActionEvent.
                                             Constructor
TextArea ta = new TextArea( )
TextArea ta = new TextArea(String str )
TextArea ta = new TextArea(String str, in heightchar,int widthchar,int scrollbar )

                                               Methods

1. void append(String str) :-It appends the string specified by str to the end of current text.
2. void insert(String str int index) :-It insert the string specified by str till index value.



JWT
                                                                  85


3.void replaceRange(String str, int startindex,int endindex)

//program that demonstrate TEXTAREA

import java.awt.*;
import java.awt.event.*;
class TextAreaEvents extends Frame implements ActionListener
{
String str="";
private TextArea ta;
private TextArea tb;
Button b;
TextAreaEvents()
{
setTitle("Text Field ");
setLayout(new FlowLayout());
b=new Button("COPY");
ta = new TextArea(str,10,10,TextArea.SCROLLBARS_BOTH);
tb = new TextArea(str,10,15,TextArea.SCROLLBARS_VERTICAL_ONLY);
add(ta);
add(b);
add(tb);
b.addActionListener(this);
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
      if(ae.getSource()==b)
        {
          tb.append(ta.getSelectedText());
        }
}
public static void main(String[] args)
  {
TextAreaEvents t = new TextAreaEvents();
    }
}




JWT
                                                                                               85




Layout managers: In Java Layout manager is an interface used to set the GUI components in
a container. It also positioning each GUI component in a container by using a          method
setLayout( ). If we don't specify the layout, then a default layout manager(FlowLayout) is set
automatically.


   1. FlowLayout: This is a default layout manager. It layout the components from left to
       right and top to bottom with a small space between each component.

                                         Constructor
FlowLayout( )
FlowLayout(int alignment) alignment is either FlowLayout.LEFT, FlowLayout.CENTER,
FlowLayout.RIGHT.

Example : Refer the program of checkbox control

   2. Border Layout: It sets the components to the edges of the window.i.e four sides of the
       container and center of the container using the layout method called setLayout( ). It
       defines the following constants to specify the region.BorderLayout.NORTH,
       BorderLayout.SOUTH         ,   BorderLayout.CENTER,        BorderLayout.EAST         and
       BorderLayout.WEST
                                        Constructors
BorderLayout ( ): The first form creates a default BorderLayout
BorderLayout (int horiz, int vert): The second form allows you to specify the horizontal and



JWT
                                                                     85


vertical space between each component.
//program to demonstrate the border layout

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BorderLayoutDemo extends JFrame
{
private JButton b1,b2,b3;
private JTextField tf;
private JTextArea ta;
private String str="This is \n demonstration of \n Border Layout";
  public BorderLayoutDemo()
   {
Container con = getContentPane();
BorderLayout border = new BorderLayout();
con.setLayout(border);
b1 = new JButton("WEST BUTTON");
b2 = new JButton("EAST BUTTON");
b3 = new JButton("SOUTH BUTTON");
tf = new JTextField("TEXT FIELD AT NORTH PLACE");
ta = new JTextArea(str);
con.add(b1,BorderLayout.WEST);
con.add(b2,BorderLayout.EAST);
con.add(ta,BorderLayout.CENTER);
con.add(b3,BorderLayout.SOUTH);
con.add(tf,BorderLayout.NORTH);
setSize(300,300);
setVisible(true);
     }
public static void main(String[] args)
{
       BorderLayoutDemo borderDemo = new BorderLayoutDemo();
//for closing window
    borderDemo.addWindowListener(
        new WindowAdapter() {
       public void windowClosing( WindowEvent event )
        {
           System.exit( 0 );
         }
} // end anonymous inner class

); // end
}
}


JWT
                                                                                           85




   3. GridLayout :This layout set the component in a two dimension grid. We must specify
       the number of rows and columns in the constructor.
                                          Constructors
GridLayout ( )
GridLayout (int rows, int cols)
GridLayout ( int rows, int cols, int hori, int vert)
rows=number of rows
cols=number of columns
hori=horizontal space
vert=vertical space b/w components.

//program that demonstrate the GridLayout

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GridLayoutDemo extends JFrame
{
static final int n=4;
private JButton buttons[];
String str[]={"1","2","3","4","6","7","8","9","0","ADD","SUB","DIV","MUL","EQUALS"};
public GridLayoutDemo()
{
setTitle("GridLayout-Claculator-GUI");
buttons = new JButton[str.length];
Container con = getContentPane();
GridLayout gridlayout = new GridLayout(n,n);
con.setLayout(gridlayout);
for( int i=0; i<str.length; i++)



JWT
                                                                                           85


{
buttons[i]=new JButton(str[i]);
con.add(buttons[i]);
}
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
GridLayoutDemo grid = new GridLayoutDemo();

//for closing window
grid.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent event )
{
System.exit( 0 );
}
} // end anonymous inner class

); // end
}
}




    4. CardLayout :-It stores several different layouts. Each layout is being thought as
        separate layout in a card desk.
                                          Constructor
CardLayout( )
CardLayout(int horz, int vert)




JWT
                                                                                           85


The panels are used to add the cards by using the method add(Component panel obj, Object
name)

                                      Methods
void first (Container deck)
void last (Container deck)
void next (Container deck)
void previous (Container deck)
void show(Container deck,String cardName)

//program demonstrate cardlayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo extends JFrame implements MouseListener,ActionListener
{
JCheckBox cse,csit,ece;
JPanel osCards;
CardLayout card;
JButton win,other;
public CardLayoutDemo()
{
Container con = getContentPane();
win = new JButton("Windows");
other = new JButton("Others");
con.add(win);
con.add(other);
card = new CardLayout();
osCards = new JPanel();
osCards.setLayout(card);//set panel to card layout
cse=new JCheckBox("CSE",null,true);
csit=new JCheckBox("CSIT");
ece=new JCheckBox("ECE");
//add windows check boxed to a panel
JPanel winPanel = new JPanel();
winPanel.add(cse);
winPanel.add(ece);
JPanel otherPanel = new JPanel();
otherPanel.add(csit);
//add panel to card deck panel
osCards.add(winPanel,"Windows");
osCards.add(otherPanel,"Others");
//add cards to main container
con.add(osCards);
//register to receive events
win.addActionListener(this);



JWT
                                              85


other.addActionListener(this);
//add mouse listener
addMouseListener(this);
setSize(300,300 );
setVisible( true );

}
public void mousePressed(MouseEvent me)
{
card.next(osCards);
}
public void mouseClicked(MouseEvent me)
{
//card.next(osCards);
}

public void mouseEntered(MouseEvent me)
{
//card.next(osCards);
}
public void mouseExited(MouseEvent me)
{
//card.next(osCards);
}

public void mouseReleased(MouseEvent me)
{
//card.next(osCards);
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==win)
{
card.show(osCards,"Windows");
}
else
{
card.show(osCards,"Other");
}
}
public static void main(String[] args)
{
CardLayoutDemo card = new CardLayoutDemo();
}
}



JWT
                                                                                                85



Event handling

Event: An event is an Object that describes a state change in a source. An event is an sequence
interaction with the GUI component like Button, CheckBox, Mouse Click etc.
Event source: A source is an object that generates an event.
Event listener:     A listener is an object that is notified when an event occur. It has two
requirements.
1. It must have been registered with one or more source to receive notifications about the event.
2. It must implements methods define in Listeners
The following are the event listener interfaces and classes are defined in java.awt.event
package.

1)ActionListener      2)ItemListener        3)AdjustmentListener       4)ComponenetListener
5)ContainerListener           6)FocusListener          7)KeyListener         8)MouseListener
9)MouseMotionListener 10)TextListener 11)WindowListener.
Event classes: Event classes are used to handle the event handling mechanism.The EventObject
is a super class of all event class defines in java.util.
                                             Constructor
1.EventObject(Object x)
                                                methods

1 . ObjectSource( ) :-It returns the source of the event.
2 . String toString( ) :- It returns the string equivalent of the event.

The class AWTEvent is a subclass of EventObject define in java.awt. It is a super class of all
event delegation model

1)ActionEvent 2)ItemEvent 3)AdjustmentEvent 4)ComponenetEvent 5)ContainerEvent
6)FocusEvent7)KeyEvent8)MouseEvent 9)MouseMotionEvent 10)TextEvent
11)WindowLEvent.

    1. ActionEvent : This event is occurred when an action occur on Button, List, TextArea,
        TextField controls etc.It sends the object to the ActionListener interface to implement the
        event through an abstract methods actionPerformed(ActionEvent ae) which must be
        implemented to handle the action event occur.
                              example----Refer the calculator program.



JWT
                                                                                            85


   2. ItemEvent :-This event is occurred when an action occur on checkbox, choice controls
        etc.It sends the object to the ItemListener interface to implement the event through an
        abstract methods itemStateChaged(ItemEvent ae) which must be implemented to
        handle the action event occur.
                     example----Refer the checkbox/choice control program.

   3.   MouseEvent Class: It is a subclass of InputEvent class to handle the mouse events
        such as mouse click, Mouse move ,mouse drag ...etc.
                                              Methods
1. int getX( ):-It returns the X co-ordinate of the mouse when an event occur.
2. int getY( ):-It returns the Y co-ordinate of the mouse when an event occur.
MouseListener interface :-This interface consists five methods to handle mouse events
1)void mouseClicked(MouseEvent me) :-It invokes when mouse clicked/pressed/released.
2)void mouseEntered(MouseEvent me) :-It invokes when mouse Entered.
3)void mouseExited(MouseEvent me) :-It invokes when mouse Exited.
4)void mousePressed(MouseEvent me) :-It invokes when mouse Pressed.
5)void mouseReleased(MouseEvent me) :-It invokes when mouse Released.

MouseListener interface: This interface consists two methods to handle mouseEvents

1) void mouseDragged(MouseEvent me) :-It invokes when mouse dragged.
2) void mouseMoves(MouseEvent me) :-It invokes when mouse moves.
//program that illustrate the Mouse event and MouseListeners

public class MouseEvents extends Applet implements MouseListener,MouseMotionListener
{
        String msg=" ";
        int mouseX=0,mouseY=0;
        public void init()
        {
                addMouseListener(this);
                addMouseMotionListener(this);
        }
        public void mouseClicked(MouseEvent me)
        {
                mouseX=0;
                mouseY=0;
                msg="Mouseclicked";



JWT
                                                                   85


            repaint();
      }
      public void mouseEntered(MouseEvent me)
      {
              mouseX=0;
              mouseY=0;
              msg="mouseEntered";
              repaint();
      }
      public void mouseExited(MouseEvent me)
      {
              mouseX=0;
              mouseY=0;
              msg="mouseExited";
              repaint();
      }
 public void mousePressed(MouseEvent me)
      {
              mouseX=me.getX();
              mouseY=me.getY();
              msg="mousedown";
              repaint();
      }
      public void mouseReleased(MouseEvent me)
      {
              mouseX=me.getX();
              mouseY=me.getY();
              msg="Up";
              repaint();
      }
      public void mouseDragged(MouseEvent me)
      {
              mouseX=me.getX();
              mouseY=me.getY();
              msg="*";
              showStatus("dragging mouse at"+mouseX+","+mouseY);
              repaint();
      }
     public void mouseMoved(MouseEvent me)
      {
     showStatus("moving mouse at"+me.getX()+","+me.getY());
      }
     public void paint(Graphics g)
      {
              g.drawString(msg,mouseX,mouseY);
      }



JWT
                                                                                                85


}

      4. KeyEvent class: This event is generated when key board input occurs. There are three
types of key events. Which are identified by integers as follows.
1) KEY_PRESSED
2) KEY_RELEASED
3) KEY_TYPED
                                            Methods

1) char getKeyChar( ) :-returns the character that was entered.
2) int getKeyCode( ):-It returns the characters code.

Key Listener interface:-It defines three abstract methods as follows

1) void KeyPressed(KeyEvent ke):-It invoked when key Pressed.
2) void KeyReleased(KeyEvent ke):-It invoked when key Released.
3) void KeyTyped(KeyEvent ke):-It invoked when key Typed.

//program that demonstrate the key event, KeyListeners

public class KeyEventDemo extends JApplet implements KeyListener
{
String msg =" ";
int x=50,y=50;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Released");
}
public void keyTyped(KeyEvent ke)
{
showStatus("Key Typed");
msg=msg+ke.getKeyChar();
repaint()
;


JWT
                                                                                          85


}
public void paint(Graphics g)
{
g.setColor(Color.red);
g.drawString(msg,x,y);
}
}




ADAPTER CLASSES: Adapter classes are useful when we want to receive and process only
some of the events methods of event listeners interface. For that we must extends the Adapter
classes   which        implements   those   methods   which   you   required.   for   example
mouseListenerconsists five methods. If we want to implement only two of them, then we must
extends mouseAdapter. Adapter classes are defined in java.awt.event. Some of the adapter
classes are follows.
1)ComponentAdapter 2)ContainerAdapter 3)FocusAdapter 4)KeyAdapter


JWT
                                                                                              85


5)MouseAdapter 6)MouseMotionAdapter 7)WindowAdapter.
public class AdapterDemo extends Applet
{
public void init()
{
addMouseListener(new my(this));
addMouseMotionListener(new myadd(this));
}
}
class my extends MouseAdapter
{
AdapterDemo a;
public my(AdapterDemo p)
{
this.a=p;
}
public void mouseClicked(MouseEvent me)
{
a.showStatus("Mouse Clicked");
}
}
class myadd extends MouseMotionAdapter
{
AdapterDemo a;
public myadd(AdapterDemo p)
{
this.a=p;
}
public void mouseDragged(MouseEvent me)
{
a.showStatus("Mouse Dragged");
}
}




                                  SWING CONTROLS

   1. JLabel :- It displays the information about the controls such as Textfield, Icon etc.

                                         Constructors
   JLabel lab1 = new JLabel(Icon i)


JWT
                                                           85


   JLabel lab2= new JLabel(String str,Icon i)
   JLabel lab3 = new JLabel(String str,Icon i int align)

      Where,
      Icon = ImageIcon object(path of image file)
      str = Name of the Label and
      align = Label.LEFT, Label.RIGHT, Label.CENTER

                                        Methods
   1.int getIcon( )
   2.String getText( )
   3.void setIcon( )
   4.void setText( )

//programs to demonstrate JLabel

import java.awt.*;
import javax.swing.*;
class LabelExample extends JFrame
{
public LabelExample()
{
setTitle("Label Demos");
Container c = getContentPane();
c.setLayout(new FlowLayout());
JLabel l0= new JLabel();
JLabel l1=new JLabel("Username");
JLabel l2=new JLabel("Password");
JLabel l3=new JLabel("Marks",Label.RIGHT);
c.add(l0);
c.add(l1);
c.add(l2);
c.add(l3);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
LabelExample label = new LabelExample();
label.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}




JWT
                                                                                        85




   2. JTextField :- The Swing text extends JComponent.It edit one line of text field.


                                        Constructors
      JTextField t1 = new JTextField( )
      JTextField t2 = new JTextField(int size )
      JTextField t3 = new JTextField(String str,int size)
      JTextField t4 = new JTextField(String str)
                                          Methods
      1. String getText( )
      2. void setText( )
//programs for JTextField
/* <applet code="TextFieldDemo.class" width="200" height="200"></applet> */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldDemo extends JApplet implements ActionListener
{
private JTextField text;
public void init()
{
Container con = getContentPane();
con.setLayout(new FlowLayout(FlowLayout.CENTER));
text = new JTextField(10);
con.add(text);
text.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
showStatus(text.getText());
}
}




JWT
                                                                                         85




   3.     JButton: Swing buttons are subclasses of AbstractButton class, which extends
         JComponent.

                                         Constructors
         JButton b1 = new JButton( )
         JButton b2= new JButton(Icon i )
         JButton b3 = new JButton(String str )
         JButton b4 = new JButton(String str,Icon i )
                                            Methods
        1.void setDisabledIcon(Icon i)
        2.void setPressedIcon(Icon i)
        3.void setSelectedIcon(Icon i)
        4.void setRolloverIcon(Icon i)
        5.void setText( String str)
        6.String getText( )

//programs for JButton with events
//<applet code="ButtonDemo.class" width="200" height="200"></applet>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo extends JApplet implements ActionListener
{
private JButton b1,b2;
public void init()
{

Container con = getContentPane();
con.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel label = new JLabel("Are you Sure Want to Submit");
b1 = new JButton("YES");


JWT
                                                                    85


b2 = new JButton("NO");
con.add(label);
con.add(b1);
con.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
    showStatus(ae.getActionCommand());
   JOptionPane.showMessageDialog(null,"You Clicked :" +
    ae.getActionCommand());
  }
}




4. JCheckBox :- It is used to select multiple options.
                                          Constructors
   JCheckBox jc1 = new JCheckBox ( )
   JCheckBox jc2 = new JCheckBox (Icon I,Boolean state )
   JCheckBox jc3 = new JCheckBox (String str )
   JCheckBox jc4 = new JCheckBox ( String s, Boolean state)
   JCheckBox jc5 = new JCheckBox ( String s,Icon I,Boolean state)

                                        Methods
    1.   Object getItem ( )

//program for JCheckBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CheckBoxExample extends JFrame implements ItemListener
{
JTextField text;

JCheckBox cb1,cb2,cb3;

CheckBoxExample()


JWT
                                                    85


{
Container con = getContentPane();
con.setLayout(new FlowLayout());

cb1= new JCheckBox("C");
cb2= new JCheckBox("C++");
cb3= new JCheckBox("JAVA");
text = new JTextField(10);
con.add(cb2);
con.add(cb3);
con.add(cb1);
con.add(text);

setSize(300,300);
setVisible(true);

cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
text.setText(cb.getText());
}
public static void main(String[] args)
{
CheckBoxExample checkbox = new CheckBoxExample();

//closing the window
checkbox.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent event )
{
System.exit( 0 );
}
} // end anonymous inner class
); // end
}
}




JWT
                                                                                            85




5. JRadioButton :- It is a immediate super class of JToggleButton which provides two state
   buttons. Only one of the radio button is selected.ButtonGroup class is instantiate to create
   button group and then add the radio buttons into the ButtonGroup method add( ).
                                        Constructors

       JRadioButton r1 = new JRadioButton(Icon i)
       JRadioButton r2 = new JRadioButton(String str,Icon i)
       JRadioButton r3 = new JRadioButton(String str)
       JRadioButton r4 = new JRadioButton(String str,Icon I, Boolean state)
//program for JRadioButton
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class RadioButtonDemo extends JFrame implements ActionListener
{
private String msg = "";
private JRadioButton r1,r2,r3;
private ButtonGroup bg;
private Container c;
Graphics g;
public RadioButtonDemo()
{
setLayout(new FlowLayout());
c = getContentPane();
r1 = new JRadioButton("RED");
r2 = new JRadioButton("GREEN");
r3 = new JRadioButton("BLUE");


JWT
                                                        85


bg = new ButtonGroup();
c.add(r1);
c.add(r2);
c.add(r3);
bg.add(r1);
bg.add(r2);
bg.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);
setSize(400,400);
setVisible(true);
c.setBackground(Color.pink);
}
public void actionPerformed(ActionEvent ie)
{
msg=ie.getActionCommand();
if(msg.equals("RED"))
{
//g.drawString(msg,50,170);
c.setBackground(Color.RED);
}
else if(msg.equals("GREEN"))
{
//g.drawString(msg,50,170);
c.setBackground(Color.GREEN);
}
else if(msg.equals("BLUE"))
{
//g.drawString(msg,50,170);
c.setBackground(Color.BLUE);
}
}
public static void main(String[] args)
{
RadioButtonDemo radio = new RadioButtonDemo();
//for closing window
radio.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}




JWT
                                                                                       85




6. JComboBox :- It is a combination of textfield and a drop-down list which extends
   JComponents. It display only one entry to the user to select from the list.

                                 Constructor
      JComboBox jc1 = new JComboBox( )
      JComboBox jc2 = new JComboBox(Vector v )

                                        Methods
   1. void addItem(Object obj):- This method is used to add the items into the list.




//program for JComboBox
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ComboBoxDemo extends JFrame implements ItemListener
{
JLabel label;
JComboBox jc;
//ImageIcon csit,ece,cse,mech,eee;
ComboBoxDemo()
{
Container con = getContentPane();
con.setLayout(new FlowLayout(FlowLayout.LEFT));
jc= new JComboBox();
jc.addItem("CSIT");
jc.addItem("ECE");
jc.addItem("CSE");
jc.addItem("MECH");
jc.addItem("EEE");


JWT
                                                                                                85


con.add(jc);
jc.addItemListener(this);
setSize(400,400);
setVisible(true);
}
public void itemStateChanged(ItemEvent ie)
{
Object s = jc.getSelectedItem();
//label.setIcon(new ImageIcon(s + ".gif"));
JOptionPane.showMessageDialog(null,"You Clicked:"+s);
}
public static void main(String[] args)
{
ComboBoxDemo combo = new ComboBoxDemo();
//closing the window
combo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}




7. Scroll Pane: It is a component that presents a rectangular area in which a component is
viewed with horizontal and vertical scroll bars are provided. It is a subclass of JComponent.

                                          Constructor
1. JScrollPane (Component comp)
2. JScrollPane (int vsb,int hsb)
3. JScrollPane (Component comp, int vsb, int hsb)
Here the vsb and hsb defines the constants vertical and horizontal scroll bars respectively. Such
as follows
1.HORIZONTAL_SCROLLBAR_ALWAYS
2.HORIZONTAL_SCROLLBAR_AS_NEEDED
3.VERTICAL_SCROLLBAR_ALWAYS


JWT
                                                                   85


4.VERTICAL_SCROLLBAR_AS_NEEDED

                                  Steps to create the scrollPane
1.Create a JComponent object
2.Create a JScrollPane object.
3.add the scroll pane object to the applet container
//Programs for JScrollPane
public class ScrollPaneDemo extends JApplet
{
public void init()
{
Container con = getContentPane();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(20,20));
int b=0;
for(int i=0;i<20;i++)
{
for(int j=0;j<20;j++)
{
JButton button = new JButton("Button"+b);
++b;
panel.add(button);
}
}
//add panel to the scroll bar
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll = new JScrollPane(panel,v,h);
//add scroll pane to the container
con.add(scroll,BorderLayout.CENTER);
}
}




JWT
                                                                                               85




8. Trees :- A Tree is a component that presents a hierarchical view of data. Trees are expands
 and Collapse. Trees can be implemented in swing by using JTree class which extends
 JComponent.

                                       Constructor
JTree tr1 = new JTree(Hashtable ht): It creates a tree in which the node are hashtable
elements.
JTree tr2 = new JTree(TreeNode tn): It creates a tree in which the node is the tree node
elements.
JTree tr3 = new JTree(Object obj[]):It creates a tree in which the node are array of Objects
elements.
JTree tr4 = new JTree(vector v): It creates a tree in which the node are Vector elements.


JTree generates the addTreeExapansion Listener (TreeExpansionListener tel ) and
removeTreeExpansionListener( TreeExpansionListener tel) to allow register and unregister
the events.
                                   Procedure to create the Tree
1.Create the JTree Object.
2.Create the JScrollPane object.
3.Add Tree to the Scroll pane.
4.Add the scroll pane to the container of the applet.
Program for JTree
/* <applet code="TreeDemo.class" width="400" height="400"></applet> */
import java.awt.*;


JWT
                                                                        85


import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class TreeDemo extends JApplet
{
      JTree tree;
 JTextField tf;
public void init()
{
Container con = getContentPane();
con.setLayout(new BorderLayout());
//create a tree of top node
  DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
   //create a sub tree of "A"
  DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
  top.add(a);
  DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
  a.add(a1);
  DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
  a.add(a2);
   //create a sub tree of "B"
  DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
  top.add(b);
  DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
  b.add(b1);
  DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
  b.add(b2);
  tree = new JTree(top);
  //add tree to a scroll pane
  int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
  int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
  JScrollPane scroll = new JScrollPane(tree,v,h);
  //add scroll pane to the container
  con.add(scroll,BorderLayout.CENTER);
  //add textfield to applet
  tf = new JTextField("",20);
  con.add(tf,BorderLayout.SOUTH);
  //handling mouse clicks
  tree.addMouseListener(new MouseAdapter(){
  public void mouseClicked(MouseEvent me){
   doMouseClicked(me);
  }
  });
  }
 void doMouseClicked(MouseEvent me)
  {



JWT
                                                                                               85


    TreePath tp = tree.getPathForLocation(me.getX(),me.getY());
       if(tp!=null)
     tf.setText(tp.toString());
      else
      tf.setText("");
}
}




    9. JTabbed Panes: It is a component that groups the components into a folder, each folder
    has the title. When a user selects a folder it contents become visible. Only one folder can be
    selected. It is mainly used in a system configuration options.

                             JTabbedPane tbp = new JTabbedPane( )

It defines a method called addTab(String str, Component comp) where str represents the title
of the tab and comp specify the components.

                                Procedure to create the JTabbedPane

1.Create the JTabbedPanes object.
2.Call the addTab( ) method to add tab to the pane,
3.repeat step 2 for each.
4.add tabbed pane to the content pane(container) of the applet.
//program to create JTabbedPane
public class TabbedPanes extends JApplet
{
public void init()
{


JWT
                                            85


System.out.println("init.........");
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities",new CitiesPanel());
jtp.addTab("Colors",new ColorsPanel());
jtp.addTab("Flavors",new FlavorsPanel());
getContentPane().add(jtp);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1= new JButton("Hyderabad");
add(b1);
JButton b2= new JButton("Shadnagar");
add(b2);
JButton b3= new JButton("Secunderabad");
add(b3);
}
}
class ColorsPanel extends JPanel
{
public ColorsPanel()
{
JCheckBox c1 = new JCheckBox("RED");
add(c1);
JCheckBox c2 = new JCheckBox("GREEN");
add(c2);
JCheckBox c3 = new JCheckBox("BLUE");
add(c3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jc = new JComboBox();
jc.addItem("Vanilla");
jc.addItem("Chocolate");
jc.addItem("Strawberry");
add(jc);
}
}




JWT
                                                                                                 85




10. JTable : A table is a component that displays a data in rows and columns.Tables extends the
JComponent. We can drag the columns and resize each columns.
                                            Constructor

JTable (Object data[ ][ ] , Object colHeads [ ]): It takes the data in two-dimension array and
colheads is the name of the columns
                                  Steps to create the Tables
1.Create a JTable Object.
2.Create a JScrollPane object object.
3.add table to the scroll pane
4.add the scroll pane to the container of the applet
//programs to create the table
public class Table extends JApplet
{
public void init()
{
Container con = getContentPane();
con.setLayout(new BorderLayout());
final String[] colHeads = {"Name","RollNumber","Dept","Percentage"};
final Object[][] data ={
{"Feroz","1214","CSIT","50.05%"},
{"Vijay","1507","CSE","70.05%"},
{"Ramesh","0414","ECE","80.12%"},
{"Riaz","0344","MECH","90.78%"}
};



JWT
                                                                                         85


JTable table = new JTable(data,colHeads);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll = new JScrollPane(table,v,h);
con.add(scroll,BorderLayout.CENTER);
  }
}




11. Menu: - In java swing menus can be created by using a class JMenu.It contains the
necessary methods to manage Menu bars.
                                         Constructors

 JMenu m = new JMenu(String s ):-It creates the menu in the menu bar.
 JMenuItem mi = new JMenuItem (String s):-It is used to add the menu item in the menu.
        Using add( ) method.
                                          Methods
   i. void addSeparator():-It separates the menu item in the menu
   ii. void setMnemonics(char c):-It create a short-key to access to the menu

//program for Menu

public class MenuTest
{
public static void main(String[] args)
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame with a sample menu bar.


JWT
                                                                85


*/
class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle("MenuTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

JMenu fileMenu = new JMenu("File");
JMenuItem newItem = fileMenu.add(new TestAction("New"));

// demonstrate accelerators

JMenuItem openItem = fileMenu.add(new TestAction("Open"));
openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
InputEvent.CTRL_MASK));

fileMenu.addSeparator();

saveAction = new TestAction("Save");
JMenuItem saveItem = fileMenu.add(saveAction);
saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_MASK));

saveAsAction = new TestAction("Save As");
JMenuItem saveAsItem = fileMenu.add(saveAsAction);
fileMenu.addSeparator();

fileMenu.add(new
AbstractAction("Exit")
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
// demonstrate checkbox and radio button menus

readonlyItem = new JCheckBoxMenuItem("Read-only");
readonlyItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
boolean saveOk = !readonlyItem.isSelected();
saveAction.setEnabled(saveOk);



JWT
                                                                            85


saveAsAction.setEnabled(saveOk);
}
});

ButtonGroup group = new ButtonGroup();

JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
insertItem.setSelected(true);
JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");

group.add(insertItem);
group.add(overtypeItem);

// demonstrate icons

Action cutAction = new TestAction("Cut");
cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
Action copyAction = new TestAction("Copy");
copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
Action pasteAction = new TestAction("Paste");
pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif"));

JMenu editMenu = new JMenu("Edit");
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.add(pasteAction);

// demonstrate nested menus

JMenu optionMenu = new JMenu("Options");

optionMenu.add(readonlyItem);
optionMenu.addSeparator();
optionMenu.add(insertItem);
optionMenu.add(overtypeItem);

editMenu.addSeparator();
editMenu.add(optionMenu);
// demonstrate mnemonics

JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');

JMenuItem indexItem = new JMenuItem("Index");
indexItem.setMnemonic('I');
helpMenu.add(indexItem);



JWT
                                                               85



// you can also add the mnemonic key to an action
Action aboutAction = new TestAction("About");
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
helpMenu.add(aboutAction);

// add all top-level menus to menu bar

JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);

// demonstrate pop-ups
popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
// the following line is a workaround for bug 4966109
panel.addMouseListener(new MouseAdapter() {});
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
private Action saveAction;
private Action saveAsAction;
private JCheckBoxMenuItem readonlyItem;
private JPopupMenu popup;
}
/**
A sample action that prints the action name to System.out
*/
class TestAction extends AbstractAction
{
public TestAction(String name) { super(name); }
public void actionPerformed(ActionEvent event)
{
System.out.println(getValue(Action.NAME) + " selected.");
}
}




JWT
                                                                                               85




                  Difference between AWT Controls and SWING Controls

1) Swing is a set of classes that provides more powerful and flexible functionality than in
possible with the standard AWT components.
2) Swing GUI components from package javax.swing.
3) Swing components are written, manipulated and displayed completely in Java,so they are
called PURE JAVA COMPONENTS.
4) It provides the functionality more than awt facilities such as JTrees, JTable, JTabbedPanes and
ScrollPane.
5) The main difference between AWT and SWING is that AWT components programs are tied
to the local system and provides the different look-- n –feel on every Java platforms.Hence they
are called HeavyWeight Components.
Where as, swing components programs gave same look-- n –feel in any Java platforms so, they
are called Lightweight components.
6) The fundamental concepts of Swing is JApplet which extends Applet.

///program to create a student form using swing Components(All Controls)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Form extends JFrame
{
JTextField name_t,rno_t;
JLabel name_lb,rno_lb,branch_lb,gender_lb,dob_lb,hobbies_lb,languages_lb;


JWT
                                                                           85


JComboBox branch_com,yy_com,mm_com,dd_com;
JRadioButton m,f;
JList hobbies_lst;
JCheckBox eng,hin,tlg,urd;
JButton submit,cancel;
public Form()
{
name_t = new JTextField(10);
rno_t = new JTextField(10);
name_t.setBackground( Color.yellow);
rno_t.setBackground( Color.yellow);
name_lb = new JLabel("Name:");
rno_lb = new JLabel("Rollnumber:");
branch_lb = new JLabel("Branch:");
gender_lb = new JLabel("gender:");
dob_lb= new JLabel("Date of Birth:");
hobbies_lb = new JLabel("Hobbies:");
languages_lb = new JLabel("Languages:");
String br_name[]={"CSIT","CSE","ECE","MECH","EEE"};
branch_com= new JComboBox(br_name);
yy_com = new JComboBox();
for(int i=1982;i<=2008;i++)
{
Integer a = new Integer(i);
yy_com.addItem(a.toString());
}
String mm_name[]={"JAN","FEB","MARCH","APRL","MAY","JUNE","JULY","AUG"};
mm_com = new JComboBox(mm_name);
String dd_name[]={"01","02","03","04","05","06","07","08","09","10"};
dd_com= new JComboBox(dd_name);
eng=new JCheckBox("ENGLISH");
hin=new JCheckBox("HINDI");
tlg=new JCheckBox("TELUGU");
urd=new JCheckBox("URDU");
ButtonGroup bg = new ButtonGroup();
m=new JRadioButton("MALE");
f=new JRadioButton("FEMALE");
bg.add(m);
bg.add(f);
String hb_name[]={"CRICKET","FOOTBALL","HOCKEY"};
hobbies_lst = new JList(hb_name);
submit= new JButton("Submit");
cancel= new JButton("Cancel");

Container c = getContentPane();
c.setBackground( Color.lightGray);



JWT
                                                     85


c.setLayout(new FlowLayout());
c.add(name_lb);
c.add(name_t);
c.add(rno_lb);
c.add(rno_t);
c.add(branch_lb);
c.add(branch_com);
c.add(gender_lb);
c.add(m);
c.add(f);
c.add(dob_lb);
c.add(yy_com);
c.add(mm_com);
c.add(dd_com);
c.add(hobbies_lb);
c.add(hobbies_lst);
c.add(languages_lb);
c.add(eng);
c.add(hin);
c.add(tlg);
c.add(urd);
c.add(submit);
c.add(cancel);
setSize(300,250);
setVisible(true);
}

public static void main(String[] args)
{
Form f = new Form();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
}
}




JWT
      85




JWT

				
DOCUMENT INFO