Anda di halaman 1dari 75

1.

Basic HTML
1. HTML is pretty straight forward, powerful and complex applications that it can be used to build. 2. Basic principle is consists of some content, usually a mixture of text and images and then apply formatting information to it. 3. The processing may take the form of display on the screen, sending it to a printer or reading the page to a visually impaired user. 4. Web documents may contain hyperlinks to other documents. Again these are entered as simple plain text. 5. The most primitive Web pages contain just text, possibly with a few hyperlinks. 6. Basic HTML-the sort of thing that we were writing before the Web became interactive and multimedia. Features: 1. Tags are delimited by angled brackets <>. 2. They are not case sensitive <HEAD>=<head>=<hEaD> 3. Styles must be switched off by an end tag; 4. Some characters have to replaced in the text by escape sequences. 5. White space, tabs, and newlines are ignored by the browser. 6. If a browser does not understand a tag it will usually ignore it. Structures: 1. All html documents follows the same basic structure. 2. They have a head which contains control information used by the browser and server and a large body. 3. The body contains the content that displays on the screen and the tags which control how that content is formatted by the browser. Basic Document:
<HTML> <HEAD> <TITLE> A MINIMAL HTML DOCUMENT</TITLE> </HEAD> <BODY> <H1> THE LARGEST HEADINGS</H1> <P> A SAMPLE PARAGRAPH SHOWING FORMATTING AND FOLLOWED BY A LINE ACROSS THE SCREEN. </P> <HR> </BODY> </HTML>

Output:

1. The entire document is surrounded by <html>..</html> 2. If the page were not enclosed in html tags the page might be displayed as plain text with both content and formatting information on display. 3. The web page has <head></head> and <body>..</body> sections. 4. All of these tags are compulsory in HTML document that you write because of their central role in structuring the page. Commenting the Page 1. Programmers are always encouraged to document their code through the use of comments. 2. Programming languages include a mechanism called the comment that lets developers write plain text inside their code files. 3. This plain text is used to describe what the program does and sometimes, how it works. 4. Comments are the same as those used by SGML. 5. Start <! And end with >. 6. Each comment can contain as many lines of text as you like. 7. If the comment runs over a no of lines, each must start and end with - - and must not contain - - within its body. EX: <! this is comment - Which is continued - --here - -> 8. Comments can be placed in either the head or body of your document. HTML Tags <html></html>: Encloses the entire documents. <head></head>: Encloses the head of the document. The following optional tags are placed inside the head. <title></title>: Indicates the title of the document that is used as the window caption. <style></style>: The purpose of the style is to provide a common way to style all HTML elements. <link></link>: It allows users to click their way from page to page. Attributes: REL=. : Specifies the type of relationship of the link to this page. HREF=..: Specifies the address of the link. TITLE=: Specifies a title for the link. <script></script>: Encloses scripting language statements to be executed by the browser. Attributes: LANGUAGE=: Specifies which language is being used in the script such as VB Script or JavaScript. SRC=: Specifies the location of a file containing the script. <meta></meta>: It provides metadata about the HTML document. It will not be Displayed on the page but will be machine parsable. <body attribute1= attribute2=>: Encloses the main body of the document. Attributes: ALINK=: Specifies the color of the activates links in the page. VLINK=...: Specifies the color of the followed link in the page. TEXT=: Specifies the color of the text in the page. BGCOLOR=: Specifies the background color. BACKGROUND=: Specifies the background color. LEFTMARGIN=..n: Specifies the left margin for the entire page. RIGHTMARGIN=..n: Specifies the right margin for the entire page. <basefont attribute=>: Sets the default font properties for the entire page. Attributes: SIZE=: Sets the size of the font to any number between 1 and 7 with 3 being default.

COLOR=: Specifies the default font color for the page. NAME=: Specifies the typeface of the default font.
<HTML> <HEAD> <TITLE> FIRST WEB PAGE</TITLE> </HEAD> <BODY BGCOLOR=#808080 TEXT=#000000> <P> BACKGROUND COLOR IS GRAY AND TEXT COLOR IS BLACK</P> <HR> <P> <FONT COLOR=#FF0000 SIZE=4 FACE=ARIAL BLACK> ARIAL BLACK IN RED COLOR AND SIZE 4</FONT> </P> </BODY> </HTML>

Output:

<Hn></Hn>: Makes the enclosed text a heading of various sizes where n is any number ranging from 1 to 5, and 1 creates the biggest heading while 6 creates the smallest. Multimedia: <img attribute1= attribute2=> Attributes: SRC=: Specifies the URL of the image. DYNSRC=: Specifies the URL of a video clip. CONTROLS=: Adds a set of controls under the video clip. USEMAP=#map1: Tells the browser that the image is a client-side clickable image map defined under the name map1. ISMAP=: Tells the browser that the image is a server-side clickable image map. ALT=: Specifies a text string to be displayed on browsers that do not support inline images. BORDER=: Specifies the width of the border drawn around the image. If BORDER is set to 0, there will be no border even around pictures that are links. ALIGN=: Specifies the alignment of the image. Value-right or left-align the image to the specified side of the page. TOP, MIDDLE, BOTTOM, TEXTTOP, ABSMIDDLE, BASELINE and ABSBOTTOM- Specifies the vertical alignment of the image with other items on the same line. VSPACE=: Specifies the space left between the edge of the image and the items above or below of it. HSPACE=: Specifies the space left between the edge of the image and the items left or right of it. WIDTH=: Specifies the width of the image.

HEIGHT=: Specifies the height of the image. <Map attribute=></Map>: Specifies a collection of hot spot that define as client-side image map. The area tag can be used inside to define hotspots. Attributes: NAME=: Specifies the name of the map so that it can be referred to later. <Area attribute1= attribute2=></Area>: Specifies the shape and size of a hot spot to be used in the definition of a client-side image map. Used inside the Map tag. Attributes: SHAPE=: Specifies the shape of the hotspot. Possible values are RECT,RECTANGLE,CIRC,CIRCLE,POLY OR POLYGON. COORDS=: Specifies the coordinates that define the hotspots position. Two pairs of coordinates are needed for RECT, three or more pairs for POLY, and one pair of coordinates and radius for CIRC. HREF=: Specifies the URL that this hotspot points to. TARGET=: Specifies which window the link will be loaded into. The target can be a name of a frame that you specified in the Frame tag or one of the following. Values: blank : loads the link into a new blank window. parent: loads the link into the immediate parent of the document the link is in. self: loads the link into the same window. top: loads the link into the full body of the current window. <Marquee attribute1= attribute2=></Marquee>: Places a scrolling text marquee into the document. Attributes: ALIGN=: Possible values are TOP, MIDDLE OR BOTTOM. Specifies the alignment of the text around the marquee. BEHAVIOR=: Possible values are scroll(default),slide or alternate. Specifies the behavior of the marquee text. BGCOLOR=: Specifies the background color of the marquee. DIRECTION=: Possible values are left or right. Specifies the direction for the text to scroll. HEIGHT=: Specifies the height of the marquee. HSPACE=..n.: Specifies the left and right marging and outside of the marquee in pixels. LOOP..n.: Specifies the number of times the marquee will loop. Values of -1 or infinite make the marquee loop indefinitely. VSPACE=..n.: Specifies the top and bottom margin for the outside of the program. WIDTH=: Specifies the width of the marquee either in pixel or in a percentage of the screen. SCROLLAMOUNT=..n: Specifies the number of pixels between each successive draw of the marquee text. SCROLLDELAY=..n.: Specifies the number of milliseconds between each successive draw of the marquee text. <HTML> <HEAD> <TITLE>IMAGE MARQUEE</TITLE> </HEAD> <BODY> <MARQUEE BEHAVIOR="SCROLL"><IMG SRC="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg"> </MARQUEE> </BODY> </HTML>

Output:

Ex: <HTML> <HEAD> <TITLE>IMAGEMAP</TITLE> </HEAD> <BODY> <P ALIGN="CENTER"> <IMG SRC="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg" width=200 height=200 USEMAP="#MAP"> </P> <MAP NAME="MAP"> <AREA SHAPE="RECT" COORDS="0,0,250,150" HREF="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg" ALT="SUNSET"> <AREA SHAPE="RECT" COORDS="400,200,200,0HREF="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Sunset.jpg" ALT="SUNSET"> <AREA SHAPE="RECT" COORDS="400,200,200,0" HREF="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Blue hills.jpg" ALT="FULLMOON"> <AREA SHAPE="RECT" COORDS="400,150,150,400" HREF="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water lillies.jpg" ALT="PICTURE"> </MAP> </BODY> </HTML>

Output:

<Applet attribute1=value attribute2=value> parameter1 parameter2 </Applet> Attributes: ALIGN=: Possible values of LEFT, RIGHT, TOP, MIDDLE or BOTTOM. Specifies the alignment of the text around the object with respect to the object. ALT=: Specifies the text to be displayed by browsers that recognize the tag but cannot show applets. CODE=: Specifies the name of the java applet. CODEBASE=: Specifies the base address of the applet. HSPACE=..n.: Specifies the left and right margins of the outside of the applet in pixels. VSPACE=..n.: Specifies the top and bottom margin for the outside of the applet. HEIGHT=: Specifies the height of the applet in number of pixels or % of screen. Parameters: These are the applet-specific parameters that are passed as arguments to the program. They are specified as tags with the Applet tag as follows <PARAM NAME= VALUE=>

Lists: <Li attribute=>: Used to mark text as a list item in any of the following list types:<Dir>, <Menu>, <Ol>or <Ul>. Attributes: TYPE=: Specifies the type of bullet used to label the item, possible values are: DISC, CIRCLE, SQUARE, A , a, I, I, 1. VALUE=: Specifies the number assigned to the item. <Dir></Dir>: puts the enclosed items marked with<li>, in a directory listing. <Menu></Menu>: Puts the enclosed items marked with <li>, in a menu list. <Ol attribute=></Ol>: Puts the enclosed items with <li>, in numbered list. Attributes: TYPE=: Specifies the type of a numbering used to label the item. Possible values are: A,a,I,I,1. START:=: Specifies the starting values for the numbering. <Ul attribute=>: Puts the enclosed items marked with <li> in a bulleted list. Attributes: TYPE=: Specifies the type of bullet used to label the item. Possible values are DISC, CIRCLE, SQUARE. <Dl></Dl>: creates a definition list. Within this container, <dt> specifies a definition term and <dd> specifies the definition. Ex:
<HTML> <HEAD> <TITLE> ORDER LIST PROGRAM </TITLE> </HEAD> <BODY BGCOLOR=BLACK TEXT=RED> <OL START=1 TYPE=1> <LI> GRADUATION <OL START=1 TYPE=a> <LI> DEGREE <OL START=1 TYPE=I> <LI>B.SC <LI>B.COM <LI>B.A </OL> <LI> ENGINEERING <OL START=1 TYPE=I> <LI>C.S.E <LI>IT <LI>MECH <LI>CIVIL <LI>ECE <LI>EEE <LI>CHEM </OL> </OL> <LI>POST GRADUATION <UL> <LI>MCA <LI>MBA <LI>MSC </UL> </OL> </BODY>

</HTML>

Output:

General Formatting: <Address></Address>: Encloses the signature file of the author of the page. Text is displayed in italics. <B></B>: bold faces the enclosed text. <Big></Big>: Makes the enclosed text one size larger. <Blink></Blink>: Makes the enclosed text blink continuously. <Blockquote></Blockquote>: Encloses a long quote. Bothe the left and right margins are indented. <Br>: Inserts a line break. Attributes: CLEAR=: Causes the text to stop flowing around any images. Possible values are RIGHT, LEFT OR ALL. <Center></Center>: Centers the enclosed elements. This tag will center everything including images, text, tables, forms etc. <P attribute></P>: Designates the enclosed text as a plain paragraph. The end tag is optional Attributes: ALIGN=: Specifies the alignment for the paragraph. Possible values are CENTER, LEFT, RIGHT. Ex: <HTML> <HEAD> <TITLE> WEB PAGE</TITLE> </HEAD> <BODY> <P ALIGN=CENTER> THIS TEXT IS CENTER ALIGNED</P> <P ALIGN=LEFT> THIS TEXT IS LEFT ALIGNED</P> <P ALIGN=RIGHT> THIS TEXT IS RIGHT ALIGNED</P> </BODY> </HTML>

Output:

<Cite></Cite>: Encloses a citation such as the title of a book or paper. <Code></Code>: Encloses a sample of code. The text is rendered in small font. <comment></Comment>: Encloses a comment. Text inside the tags is ignored unless it contains HTML code. <Dfn></Dfn>: Encloses a definition. <Div align=></Div>: Specifies the alignment of the enclosed elements. Can be used to divide a document into sections that are aligned differently. Attributes: ALIGN=: Sets the alignment of the division. Possible values are CENTER, RIGHT, LEFT. <EM></EM>: Emphasis on the enclosed text(Italics); <I></I>: The enclosed text is italics. <Kbd></Kbd>: Specifies text to be entered at the keyboard. Text is rendered as bold and fixed-width. <Small></Small>: Makes the enclosed text one size smaller. <Strong></Strong>: Stronger emphasis on the enclosed text. <Var></Var>: Specifies a variable. Text is rendered in small fixed-width type. <S></S>: Displays text with a line through it. The <Strike> tag does exactly the same. Ex: <HTML> <HEAD> <TITLE>INFORMATION TYPE ELEMENTS</TITLE> </HEAD> <BODY> <P> SENTENCE CONTAINING A <CITE> CITE REFERNCES </CITE> </P> <BR> <P> SENTENCE CONTAINING A <CODE> CODE REFERNCES </CODE> </P> <BR> <P> THE <EM> EMPAHSIS</EM ELEMENTS LOOKS DIFFERENT </P> <BR> <P> TEXT INSIDED THE <KBD> KBD ELEMENTS WOULD TYPICALLY </KBD> DISPLAYS MONO SPACED</P><BR> <P> A SEQUENCE OF <SAMP> LITER CHAR</SAMP> COMMONLY DISPLAYS A MONOSPACE FONT</P><BR> <P> THE INSTRUCTION<STRONG>MUST BE READ</STRONG> BEFORE CONTINUING</P><BR> <P> WHEN CODING<VAR>LEFT INDENT</VAR> MUST BE A VARIABLE </P> <BR> </BODY> </HTML> Output:

<Hr attribute1= attribute2= >: Inserts a horizontal line. Attributes: SIZE=: Specifies the thickness of the line. COLOR=: Specifies the color of the line. WIDTH=: Specifies the width of the line. ALIGN=: Specifies the alignment of the line. NOSHADE=: The line is drawn solid <Font attribute=></Font>: Sets the font properties for the enclosed text. Attributes: SIZE=: Sets the size of the front to any number between 1 and 7 with 3 being default relative sizes also work. COLOR=: Specifies the color of the font. FACE=: Specifies the face of the font. <Pre></Pre>: Displays text in fixed-width type without collapsing spaces. <HTML> <HR> <HEAD> <PRE> <TITLE> FIRST WEB PAGE</TITLE> </PRE> </HEAD> <HR> <BODY> </BODY> <STRIKE> THIS TEXT WILL APPEAR WITH STRIKE </HTML> EFFECT</STRIKE>

Output:

<U></U>: The enclosed text in underlined. Try to avoid this since underlined text usually indicates a link. Ex: <HTML> <P><B><I><U> THIS TEXT WILL APPEAR IN BOLD, <HEAD> ITALICS AND UNDERLINED</U></I></B></P> <TITLE>BOLD ITALIC</TITLE> </BODY> </HEAD> </HTML> <BODY>

Output:

<Sub></Sub>: Renders the enclosed text in subscript. Ex: <HTML> <HEAD> <TITLE>SUB SCRIPT</TITLE> </HEAD> <BODY> <Sup></Sup>: Renders the enclosed text in superscript. <HTML> <HEAD> <TITLE>SUB SCRIPT</TITLE> </HEAD> Output:

<P>H<SUB>2</SUB>O IS THE CHEMICAL NAME FOR WATER</P> </BODY> </HTML>

<BODY> <P>THIS IS 5<SUP>TH</SUP> PROGRAM</P> </BODY> </HTML>

Hyperlinks: Hyperlinks is defined as the text, which linked to the webpage in the same web site to another website, so that clicking on the same text we can load the linked page into browser. You can easily differentiate between simple text and hypertext in a browser. When you bring your mouse cursor over the hypertext, the shape of the cursor will change into a hand symbol. Hypertext will also appear underlined. Hypertext can have links to web pages of the same website or a different website. Hypertext can also be linked to different parts of the same webpage using the Name attribute. Adding Hyperlink to text: In order to link some text to some other document, the following tag must be used. <a href=hello.html> click here to invoke</a> The file to which the text is linked must be specified in <a href> tag. <HTML> <P><A HREF=HELLO.HTML> CLICK HERE TO <HEAD> INVOKE HELLO.HTML</A> </P> <TITLE>SUB SCRIPT</TITLE> </BODY> </HEAD> </HTML> <BODY> Output:

2.In order to understand how hypertext works, do the following steps: 1. Type the code of main program and save it as main.html. 2. Similarly type the code of link program and save it as hello.html. 3. Open main.html in the browser. 4. Click on the hypertext click here to invoke/

Adding Hyperlinks to images: Similar to text, you can link images to some other Html document, so when the user clicks on the image, the linked Html document will be opened. <A HREF=HELLO.HTML><IMG SRC=FLOWER.JPG /></A> To link the image to the fileHello.html you have to specify the image name using <Img src=flower.jpg> tag which is again embedded within <A Href> and </A> tags. Ex: <HTML> <P ALIGN=CENTER> <HEAD> <A HREF=HELLO.HTML> <TITLE>SUB SCRIPT</TITLE> <IMG SRC=C:\WINDOWS\FLOWER.JPG </HEAD> BORDER=0 /></A> </P> <BODY> </BODY> <P ALIGN=CENTER> </HTML> CLICK HERE TO INVOKE HELLO.HTML </P> You need to perform the following steps in order to add a link to an image. 1. Type the code by using notepad. 2. Save the file as image.html. 3. Open the fileimage2.html in the browser. 4. When you take the mouse cursor over the image, it will change into a hand symbol because it is hyperlinked. Hyperlink to the different sections of the webpage: In this, how to link the text or images to different parts of the same document is known. In order to achieve this task, we need to create sections or named regions in your document which is also termed as bookmark. By using <a> tag we can create a bookmark inside a document by using Name attribute as follows. <A NAME=SECTION1></A> Any thing that appears there two tags will be considered as part of section1. The sections can create as per users choice. Every section is identified by its name. Ex: <HTML> <P> TO MAKE THIS WORK WE NEED TO SIMULATE <HEAD> THE DOCUMENT BEING VERY LONG BY USING <TITLE> ANCHORS</TITLE> MANY BREAKS</P> </HEAD> <BR><BR><BR><BR><BR><BR><BR> <BODY> <A NAME=MIDDLE></A> <A NAME=TOP></A> <HR> <P> YOU WILL KNOW HOW IT WORKS</P> <P><STRONG> MIDDLE PORTION OF THE <P><STRONG>THIS IS THE TOP PART OF THIS DOCUMENT</STRONG> DOCUMENT </STRONG> </P> </P> <P><A HREF=#BOTTOM> GO TO <P><A HREF=#BOTTOM> GO TO BOTTOM</A></P> BOTTOM</A></P> <P><A HREF=#MIDDLE> GO TO MIDDLE</A></P> <P><A HREF=#TOP> GO TO TOP</A></P> <HR> <HR> <BR><BR><BR><BR><BR><BR><BR>

<A NAME=BOTTOM></A> <P><A HREF=#BOTTOM> GO TO TOP</A></P> <HR> <P><A HREF=#TOP> GO TO MIDDLE</A></P> <P><STRONG> BOTTOM PORTION OF THE <HR> DOCUMENT</STRONG> </BODY> </P> </HTML> <A HREF> is used to create links to sections of the same document as well as links to different documents. But there is a small difference in the way user use it. For creating a link to some other document <A Href=file1.html>hello</A> For creating a link to some other document <A Href=#Section Name>hello</A>

Frame Sets
Introduction: 1. All of the web pages we have presented have the ability to link to other pages. 2. But can display only one page at a time. 3. Uses frames, which allow the browser to display more than one xhtml document simultaneously. 4. To create a set of frames in a page, we use <Frameset> and <Frames> tags. Ex: <FRAMESET ROWS=30% , *, 20%> <FRAME NAME=HEADER SRC=H1.HTML> <FRAME NAME=CONTENT SRC=H2.HTML> <FRAME NAME=FOOTER SRC=H3.HTML> </FRAMESET> In the above example, the page is divided into 3 rows. 1st frame occupies 30% of page. 2nd frame occupies the rest part. 3rd occupies the 20% of the page. Output: src indicates which page is to be displayed in the particular frame. We can divide the frame page into columns with attribute cols. <FRAMESET COLS=55%,*> <FRAME NAME=LEFT SRC=L1.HTML> <FRAME NAME=LEFT SRC=L2.HTML> </FRAMESET> Output: Iframe: 1. There is also a related element called an <iframe> that is widely supported in newer browsers. 2. The inline element <iframe> allows place a frame anywhere within a page. <IFRAME NAME=INLINECONTENT SRC=NEWCONTENT.HTML WIDTH=500 HEIGHT=200> Nested Framesets: 1. We can use the frameset element to create more complex layouts in a web page by nesting framesets. <FRAMESET COLS=110,*> <FRAME NAME=LEFT SRC=NAV.HTML> <FRAMESET ROWS=175,*> <FRAME NAME=PICTURE SRC=P.HTML> <FRAME NAME=MAIN SRC=M.HTML> </FRAMESET> </FRAMESET> Output:

Noframes: 1. Placed inside the Frameset, anything between this is viewable only by browsers that do not support frames. 2. This tag is used to create pages that are compatible with older browsers that do not support frames. <NOFRAMES> <P> THIS PAGE USES FRAMES, BUT YOUR BROWSER DOES NOT SUPPORT THEM. </P> <P> PLEASE <A HREF=NAV.HTML> THIS LINK TO BROWSE OUT SITE WITHOUT FRAMES</A> </P> </NOFRAMES>

Forms
What is a form? The form element of Html is designed to collect input from web surfers for processing on the server side. Different types of input control elements are placed inside a form to receive user input for server-side processing. A form is basically a web page with input fields that allows user to enter information. Form Processing: 1. Web page with an html form is submitted from browser. 2. The browser packages up all the data in the form and sends it over to the web server. 3. The web server receives the form data, and then passes it off to a web application to be processed. Tags: <FORM ACTION=http://www.labs.com/dummy.php method=post> </form> Action: this attribute holds the URL of the web server. Method: Determines how the form data will be sent to the server. Post: web application URL in browser address bar. Get: the form data added on the end of URL. Form-Control Elements: 1. All inputs controls are inline elements. 2. Under XHTML forms, a form may only contain block elements. 3. A form may not contain another form so no form nesting is allowed. Input-control Elements: Text Input: Most frequently used input control is the text input element that receives a text string. <FORM> FULL NAME:<INPUT TYPE=TEXT NAME=FNAME /> EMAIL:<INPUT TYPE=TEXT NAME=EMAIL /> </FORM> Radio Input: The radio element creates a single control with several buttons, only one of which can be selected at any time. Push one in, rest Pop out. <FORM> <INPUT TYPE=RADIO NAME=HOTORNOT VALUE=HOT> <INPUT TYPE=RADIO NAME=HOTORNOT VALUE=NOT> </FORM> 1. All the radio buttons associated with a given set of choices must have same name. 2. But each choice has a different value.

Checkbox Input: 1. Allow users to choose several items from a list of choices. 2. Clicking on a checkbox selects/deselects it without affecting other checkboxes. User may select all, none, or any number of checkboxes in between. <FORM> YOUR FAVOURITE SPORTS:<BR> <INPUT TYPE=CHECKBOX NAME=TENNIS>TENNIS <BR> <INPUT TYPE=CHECKBOX> BASEBALL <BR> <INPUT TYPE=CHECKBOX> WIND SURFING <BR> </FORM> Output: Password: The password element works like the text element, except that the text you type is masked. <FORM> <INPUT TYPE=PASSWORD NAME=SECRET> </FORM> Output: Select elements: Pull-down menus: When there are many choices, a pull-down can save space and make the form cleaner & cleaner. Select element is a input control for this purpose. We include any number of option elements inside a select element as the choices. <FORM> STATE:<SELECT NAME=STATENAME> <OPTION>ALABAMA</OPTION> <OPTION>ALABAMA</OPTION> <OPTION>ALABAMA</OPTION> <OPTION>ALABAMA</OPTION> </SELECT> </FORM> Sometimes options can be divided into different groups. The optgroup can separate options into groups. Selections are better organized and easier for the end user. <OPTGROUP LABEL=SALAD> <FORM> <OPTION>GARDEN SALAD</OPTION> <SELECT NAME=MENU> <OPTION>SPINACH SALAD</OPTION> <OPTION>YOUR MENU</OPTION> <OPTION>FRUIT SALAD</OPTION> <OPTGROUP LABEL=SOUP> </OPTGROUP> <OPTION>HOT&SOUR</OPTION> </SELECT> <OPTION>EGG DROP</OPTION> </FORM> <OPTION>CHICKEN NOODLE</OPTION> </OPTGROUP> Textarea element: The textarea element creates a multi-line text area that we can type into If we type more text than will fit into the text area, then a scroll bar appears. <FORM> PLEASE LET US HAVE YOUT ELEMENTS:<BR> <TEXTAREA NAME=FEEDBACK ROWS=4 COLS=60> </TEXTAREA> </FORM>

Output: The end user may type more than 4 lines, in which case a vertical scroll bar will appear, similarly for lines with more than 60 characters. The read only can be added to make an input window un-editable.

Buttons:
Submit Buttons: The submit element creates a button that allows you to submit a form. When we click this button, the browser sends the form to the web application for processing. A form may have multiple submit buttons with different values. <FORM> <INPUT TYPE=SUBMIT> </FORM> Output: The button is labeled submit by default. As an alternative to the input-based submit button, we can also use the button element to create submit buttons.
<BUTTON NAME=MYBUTTON VALUE=JOINNOW>JOIN THE CLUB </BUTTON>

Program:
<HTML> <HEAD> <TITLE> BEAN MACHINE </TITLE> </HEAD> <BODY> <FONT COLOR=RED> <H1>THE STARBUZZ BEAN MACHINE</H1> </FONT> <H3> FILL OUT THE FORM BELOW AND CLICK ORDERNOW TO ORDER </H3> <FIELDSET> <FORM> <PRE>CHOOSE YOUR BEANS: <SELECT NAME=MENU> <OPTION>HOUSE BLEND</OPTION> <OPTION>ORGANIC GUATOMALA</OPTION> <OPTION>KOYA</OPTION> TYPE:<INPUT TYPE=RADIO NAME=RADIO> GROUND <BR> TYPE:<INPUT TYPE=CHECKBOX> INCLUDE CATALOG WITH ORDER <BR> SHIP TO: <BR> NAME: <INPUT TYPE=TEXT><BR> ADDRESS: <INPUT TYPE=TEXT><BR> CITY: <INPUT TYPE=TEXT><BR> STATE: <INPUT TYPE=TEXT><BR> ZIP: <INPUT TYPE=TEXT><BR> CUSTOMER COMMENTS: <textArea name=comments rows=10 cols=50> </textArea> <br> <INPUT TYPE=BUTTON VALUE=ORDERNOW> </PRE> </FORM> </FIELDSET> </BODY> </HTML>

Output:

2.JAVA SCRIPT
What is a scripting language? Scripts are programs written in a simple and easy to use language to specify control of other programs. A scripting language allows control of one or more software applications as they are usually written in a different language. Scripts are divided into two types. There are:1. Client-side scripts 2. Server-side scripts Client-side scripts are almost always written in the java script language to control browser action. Tasks performed with client-side scripts include: Asking the browser to display information. Making the webpage different depending on the browser and browser features. Monitoring user events and specifying reactions Generating html code for parts of the page. Modifying a page in response to events. Checking correctness of user output. Replacing and updating parts of a page. Changing the style and position of displayed elements dynamically. Client-side scripting can make web pages more dynamic and more responsive. Early script languages are job control languages, GUI scripting, Text Processing languages, Application specific languages etc. What is a javascript? Javascript is a widely used scripting language originally developed by Netscape for both clientside and server side scripting Client-side java script is used widely and supported by major browsers including Netscape Navigator, Mozilla and Opera. This client-side Java script for adding dynamism and interactivity to web pages and refers to its simply as Java Script Java script is a lightweight interpreted programming language with rudimentary object-oriented capabilities. Java Script is also called as Jscript. Microsofts version of JavaScript is called as Jscript Java Script can also used outside of web pages, for example, in windows script host with Jscript (or) Mozilla. Features of JavaScript: 1. One important feature about Java Script is that it is an object-oriented language. 2. Manipulation of structured documents. 3. Another important application is checking the validity of form input so users may correct mistakes immediately. 4. Java script is multifunctional ie. It can be used at a client side as well as server side also. 5. Page embellishments and special effects. 6. Navigations systems 7. Basic mathematical calculations. 8. Java script widely used in generation of dynamic document 9. In java script, one data type can be automatically converted into other types with out explicit conversion. Difference between java & Java Script: Java script and java are similar in some ways but fundamentally different in others. Java script supports most java expression syntax and basic control-flow constructs.

In contrast to javas compile-time systems of classes built by declarations, Java script supports a runtime system based on small no of data types. Java script also supports functions without any special declarative requirements. Java is an object-oriented programming language designed for fast execution & type safety.

Java Script
Interpreted (not compiled) by client.

Java

Compile byte codes download from server, executed on client. Object-based uses built-in, extensible object, Object-oriented. Applets consist of object but no classes or inheritance. classes with inheritance. Code integrated with and embedded in html Applets distinct from Html(accessed from Html pages). Variable data types not declared(loose typing) Variable data types must be declared (Strong typing). Dynamic binding, object reference checked at Static binding object reference must exist at runtime. compile time. Cannot automatically write to hard disk. Cannot automatically write to hard disk. Elements in Java Script: Key words, statements, syntax, and grammar. Rules for expressions, variables, and literals. Underlying object mode (although navigator and livewire have different frameworks). Built-in-object and functions. Strengths of Java Script: 1. Java script offers several strengths to the programmer including a short development cycle, ease-oflearning and small size scripts. 2. These strengths meant that Java script can be easily and quickly used to extend HTML pages already on the web. Quick Development: o Because Java script does not require time-consuming compilations, scripts can be developed in a relatively short period of time. o Java-script programmers dont have to worry about creating or handling elements. Easy to learn: o Because the www, by its very nature, it is platform-independent. o Java script programs created for Netscape Navigator are not tied to any specific hardware or Operating Systems. Small overhead: o Java script programs tend to be fairly compact or are quite small, compared to the binary applets produced by java. o This minimizes storage requirements on the server or download times for the user. Weakness of Java: It has limited set of built-in-methods. Inability to protect source code from prying eyes. Java script still does not have a mature development& debugging environment. Adding java script to Html: The most popular use of java script is in web pages. Adding it is quite simple. By using <Script> element is commonly used to add script to a document. To add Java script to a web pages, you can use the following techniques: The <script> HTML tag containing the script source text. From an external file using the <SCRIPT SRC=FILENAME.JS>HTML tag and attribute. With an event handled attribute.

In a Java script: URL. The <Script> element: By using <script> element is used to add script to a document. Traditionally, the way to indicate the scripting language in use is to specify the language attribute for the tag for example. <SCRIPT LANGUAGE=JAVASCRIPT></SCRIPT> Within a <script> tag we use some output& input statements. They are Writing text in a webpage: document.writeln(string); document.writeln(string); Message box & Input box in Java Script: Window.alert(string); For reading a value: window.prompt(string, default value in the textfield); Ex: <html> </script> <head> </head> <title>javascript program</title> <body> <script language=javascript> </body> document.write(<h1> welcome to javascript </html> programming); Control flow structures in Java script: Java script supports these control structures. These include: 1) Flow control(if, if-else, switch) 2) Loops (while, do-while, for) 3) Loop control (break and continue) Flow control: If statement:- The if statements in java script basic decision-making control statement. The basic syntax of the if statement is: Syn: If(expression) { Statements block; } If the condition is true, the statement is executed otherwise, it moves on to the next statement. Ex: <html> document.write(x value is 5); <head> } <script language=javascript> </script> var x=5; </head> if(x>1) <body> { </body> document.write(x is greater than 1); </html> If-else statement: When the condition of the first statement is not met, the code in the else statement will be executed. Syn: if(expression) } { else Statement1; Statement2;

Ex: <html> document.writeln(b is big); <head> </script> <script language=javascript> </head> var a=3,b=2; <body> if(a>b) </body> document.write(a is big); </html> else If-else-if: Syn: if(expression1) statement-1; else if(expression2) statement-2; . else statement-n; Ex: else <html> window.alert(c is big); <head> </script> <script language=javascript> </head> var a=14,b=10,c=9; <body> If(a>b&&a>c) </body> window.alert(a is big); </html> else if(b>c&&b>a) window.alert(b is big); Switch:- if statements to select a statement to execute from among many alternatives. Syn: Switch(expression) { case condition-1: statatements; break; case condition-2: statatements; break; . case condition-n: statatements; break; } Ex: break; <html> case c: c =a*b; <head> document.writeln(c); <script language=javascript> break; var a=3,b=2,ch=a,c; } switch(ch) </script> { </head> case a: c =a+b; <body> document.writeln(c); </body> break; </html> case b: c =a-b; document.writeln(c);

Loops: While Loop: Loops are used to perform some block of statements are execute more than once. Syn: Initialization; while(expression) { statement; Increment/decrement; }

Ex: i++; <html> } <head> </script> <script language=javascript> </head> var i,n=5; <body> i=1; </body> while(i<=n) </html> { document.writeln(i); Do-while loop: In do-while loop, the block of statements are executed at least once if the condition is true of false. Ex: Initialization; do { statement; Increment/decrement; } while(expression); Ex: i++; <html> } <head> while(i<=n); <script language=javascript> </script> var i,n=5; </head> i=1; <body> do </body> { </html> document.writeln(i); For loop: In this loop, initialization, expressiom increment/decrement conditions are mentioned in single line. These 3 conditions/statements separated by semicolon; Syn: for(initialization;expression;iteration) { Statements; }

Ex: <html> } <head> </script> <script language=javascript> </head> var i,n=5; <body> for(i-0;i<=n;i++) </body> { </html> document.writeln(i); Loop control: Break statement: By using this, we exit a loop early. That means we skip some statements. Syn: break; (or) break loopposition(outerloop/innerloop); Ex: document.writeln(i); <html> } <head> </script> <script language=javascript> </head> var i,n=5; <body> for(i-0;i<=n;i++) </body> { </html> If(i==3) break; Continue: the continue statement tells the compiler to immediately start the next iteration of the step. Syn: continue (or) continue loop position (outerloop/innerloop). Ex: document.writeln(i); <html> } <head> </script> <script language=javascript> </head> var i,n=5; <body> for(i-0;i<=n;i++) </body> { </html> If(i==3) continue; Functions in Java script: Functions are used to encapsulate code that performs a specific task. Some-times functions are defined for commonly required tasks to avoid the repetition. Java script functions are declared with the function keyword or the statements that carry out their operations are listed in curly braces. In this functions of java script we dont use data types. Functions are set of statements, which perform a specific task. Functions may or may not return a value. Every function has a name and an argument list, which is optional. In javascript, functions are declared in the following manner, function functionName(argument list) { statement(s); } The scope of the function is defined by {} or the statements form the body of the function. Functions are not executed until they are explicitly called using function call statements. An example of function call is given below. functionName()

in case the function accepts arguments, you need to pass parameters along with function call statement in the following manner. functionName(arg1,arg2argn); Ex: <html> <script language=javascript> <head> var i,n=5; <script language=javascript> i=1; function disp() for(i=1;i<=5;i++) { { document.write(Hello world ); document.writeln(i); } disp(); disp(); } </script> </script> </head> </body> <body> </html> <h1> How to use functions</h1> Local & Global variables: The variables used in for, do-while and while loops those variables are called as Global variables because they can be accessed from any part of the Html document. local variables are those whose scope is limited within the block in which they are defined and cannot be accessed from outside that particular box. In Java script any variable, which is preceded by the keyword var is considered to be a local variables. A local variable is declared in the following manner, Ex: var num1; Ex: </head> <html> <body> <head> <h1> How to use functions</h1> <script language=javascript> <script language=javascript> function sum(num1,num2) Sum(1,2); { </script> var2=num1+num2; </body> document.write(Hello world ); </html> } </script>

Objects Overview:
Array object: Array object provides certain methods which makes easier array manipulations. toString() Converts an array to string. The array elements are separated by commas. Join(separator) Joins array elements together but separated by the separation string. Sort() Sorts the contents of an array based upon the ascii value of each character. Reverse() Reverse the contents of an array. The last element becomes first and the first element last.

Ex: <html> <head><title>Array object</title></head> <body> <h1 align=center> <script language=javascript> myArray=new Array{1,3,4,7,8,9,6,0,2}; document.write(<pre>); document.write(myArray.toString()\t:\t\t); document.write(myArray.toString()+<br>); document.write(myArray.join(-)); String Object: It provides following methods. toLowerCase() toUpperCase() subString() subString(index1,index2)` Split() charAt() charCodeAt(index) indexOf(pattern)

document.write(myArray.join(-)+<br>); document.write(myArray.reverse()\t:\t\t); document.write(myArray.reverse()+<br>); document.write(myArray.sort()\t:\t\t); document.write(myArray.sort()+<br>); document.write(<pre>); </script> </body> </html>

Converts the entire string to lowercase. Converts the entire string to uppercase. Returns a substring from a string beginning at index. Returns a sub-string from a string beginning at indes1 and ending at index2. Separates the entire string into an array of substring based upon the separator character. Returns the character at the specified index. Returns the character code(UNICODE) if the character at the specified index Returns the index of first occurrence of the substring considering the initial index at zero(0). document.write(myString.subString(7)+<br>); document.write(myString.subString(5,12)\t:\t\t); document.write(myString.subString(5,12)+<br>); document.write(myString.charAt(8)\t:\t\t); document.write(myString.charAt(8)+<br>); document.write(myString.split(first)\t:\t\t); document.write(myString.split(first)+<br>); document.write(myString.charCodeAt(1)\t:\t\t); document.write(myString.charCodeAt(1)+<br>); document.write(<pre>); </script> </body> </html>

Ex: <html> <head><title>Array object</title></head> <body> <h1 align=center> <script language=javascript> myString=new String(this is first string. This is second string); document.write(<pre>); document.write(myString.toLowerCase()\t:\t\t); document.write(myString.toLowerCase ()+<br>); document.write(myString.toUpperCase()\t:\t\t); document.write(myString.toUpperCase()+<br>); document.write(myString.subString(7)\t:\t\t);

Date Object: It provides methods to work with date and time.


getDate() getDay() getMonth() setMonth() getYear() setYear() Returns the day of the month from the date object. Returns the day of the week from the Date object, starting Monday as 1. Returns the month of the year from the Date object. Sets the month of the year for the Date object. Gets the year from the date object. Sets the year for the date object

getFullYear() setFullYear() getTime() getHours(),getMinutes(),getSeconds() setHours(),setMinutes(),setSeconds()

Returns the year in four digit format from the date object. Sets the year in four digit format for the Date object. Returns the time in milliseconds since midnight january1, 1970 from the Date object Return the hours, minutes, and seconds from the Date object Sets the hours, minutes, and seconds for the Date object

Ex: <html> <head><title>Array object</title></head> <body> <h1 align=center> <script language=javascript> myDate=new Date(); document.write(Todays date:\t); document.write(myDate.getDate ()+/+myDate.getMonth()+/+myDate.getYear()); document.write(<br>); document.write(Systems time:\t); document.write(myDate.getHours()+/+myDate.getMinuties()+/+myDate.getSeconds()); </script> </body> </html> Boolean object: Boolean object allows the creation of user defined Boolean values. You can declare the object myTrue to represent the Boolean value true. You can declare the object myFalse to represent the Boolean value false. Ex: document.write(true +true); <html> document.write(<br>); <head><title>Array object</title></head> document.write(myTrue + myTrue:\t); <body> document.write(myTrue + myTrue); <h1 align=center> </script> <script language=javascript> </body> myTrue=new Boolean(true); </html> myFalse=new Boolean(false); document.write(true + true:\t); Math object: Math object is used for performing simple and advanced arithmetic operations. Specific instances of the Math object are not created because Math is a built-in object and not an object type. Properties: Log10e This represents the base 10 logarithm of e. PI The constant PI value. E Eulers constant Log2e The base 2 logarithm of e. Ln2 The natural logarithm of2. Methods: abs(x) This method returns absolute value of x. acos(x) This method returns arc cosine value of x. asin(x) This method returns arc sine value of x. atan(x) This method returns arc tan value of x. atan2(x,y) This method returns angle of the polar

cos(x) exp(x) log(x) max(x,y) min(x,y) pow(x,y) random() round(x) sin(x) sqrt(x) tan(x)

coordinate. This method returns cosine of x. This method returns exponential of x. This method returns natural logarithm of x. This method returns maximum of x and y. This method returns minimum of x and y. This method returns x power to y. This method returns random number 0 and 1. This method returns x rounded to the closest integer. This method returns sine value of x. This method returns square root value of x. This method returns tan value of x.

Ex: <html> document.write(Absolute value of -34 <head><title>Array object</title></head> is:+Math.abs(-25)); <body> document.write(Round of 16.765 <h1 align=center> is:+Math.round(16.765)); <script language=javascript> </script> document.write(Square root of 16 </body> is:+Math.sqrt(16)); </html> Global object: Global object provides methods, which can be accessed globally, Netscape Navigator and Internet Explorer implements the global object, but do not allow it to be explicitly created using the new operator or referenced using the . Operator. Ex: <html> var a=parseInt(window.prompt(enter a value,0) <head><title>Array object</title></head> document.write(a value is+ a); <body> </script> <h1 align=center> </body> <script language=javascript> </html> Methods eval(expression) parseInt(string) parseFloat(string) isFinite(number) isNaN(number)

This method evaluates and returns the value of the expression. This method passes the string to a integer. This method passes the string as a floating point number This method returnstrue if the number is finite, otherwise false. This method returns true if the number is Nam(Not a Number), otherwise false.

CSS
Introduction:Formatting and presenting information using a w3c technology called cascading style sheets that allows document to specify the presentation of elements on a web page separately from the structure of document. This separation of structure from presentation simplifies maintaining and modifying a documents layout. It is a language, recommended by w3c and supported by major browsers for specifying presentation styles for XHTML,HTML and other documents. CSS consists of following components: Sytle selections: A style declaration is given in the form. Property: value Selectors: CSS defines selecdtors to give you multiple ways to indicate which style properties are assigned to which HTML documents. Selector { Property1:value1; Property1:value1; . Property1:value1; } Style Sheets: A style sheet is a file that contains one more style rules. Structure of a style rule. H1{font-size:200%; font-weight: bold} Inline Styles: A web developer can declare document styles in many ways. Inline styles that declare an individual elements format using attributestyle Ex: <html> <p style=font-size:20pt>AU</p> <head> <p style=font-size:20pt>AU</p> <title>Inline Styles</title> <p style=font-size:20pt>AU</p> </head> </body> <body> </html> <p> list of colleges</p> Embedded style sheets: Second technique for suing style sheets called Embedded style sheets. It contains three types <style type=text/css></script> =image/gif =text/javascript Type attribute specifies the Multipurpose Internet Mail Extension type that describes files content. Style placed in the head apply to matching elements in the entire document, not just to a single element. Ex: <html> </style> <head> </head> <title> Style sheets</title> <body> <style type=text/css> <h1 class=blue>MVGR</h1> H1{font-family:Arial, sanserif} <p> Welcome to MVGR college</p> P{font-size:18pt} </body> .blue{color:blue} </html>

Conflicting styles: Cascading sheets are cascading because styles may be defined by a user, an author or a user agent. Styles defined for parent and ancestor elements are also inherited by child and descendant elements. Em{color:blue} P em{color:red} Inheritance in which a child em element inherited the font-size property from its parent p element. However child em element had a color property that conflicted with the color property of its parent p element. Properties defined for child and descendant elements have a greater specificity than properties defined for parent and ancestor elements Ex: <html> <head> <title>More styles</title> <style type=text/css> a.nodec{text-deuration: none} a.hover{text-deuration: underline; color: red; background-color: #00FF00} </style> </head> <body> <h1> shopping list</h1> <ul> <li>milk</li> <li>bread</li> <li>pizza<em> with mushrooms </em> </li> </ul> <p><a class=nodec href=example.html> go to grocery store/m/a></p> </body> </html> Property text-deuration: none applies to all a elements whose class attribute is set to nodec. By default, browsers underline a element, but here we set text-deuration to none, it indicates that the browser should not underline hyperlinks. Specifying a style for hover, which is a psedudo-class psedoclass give the author access to content not specifically declared in the document. The hover pseudo class I activated dynamically when the user moves the mouse cursor over an element. Linking External Style sheets:To attach the three rules to a web page. You can place them in a file, such as myfile.css, and put the following link element inside the head element. <link rel=stylesheet type=text/css href=myfile.css> a {text-deuration: none} lie m {color:red; font-weight:bold; backgroung-color:#FFFFFF} ul{margin-left:2cm}
<html> <head> <link rel=stylesheet type=text/css href=styles.css/> </head> <body> <ul> <li>milk</li> <li>bread</li> <li>pizza<em> with mushrooms</em></li> </ul> <p><a href=example.html> go to the grocery store</a><p> </body> </html>

Positioning Elements: 1. Absolute 2.Relative Absolute: Controlling the positioning of elements in an XHTML document was difficult. CSS introduces the position property and a capability called Absolute positioning, which provides authors greater control over how document element are displayed. Specifying an elements position as Absolute removes the element from the normal flow and positioning the element according to the distance from the top., left, right or button margins of its containing block. The z-index attribute allows you to layer overlapping elements properly. Element that have higher z-index values are displayed in front of elements with lower z-index values. In example i.gif has the lowest z-index(1), so it displays in the background. The f element has a z-index(3), so it displays in front of the i.gif. Ex: html> <head> <title> Absolute positioning</title> </head> <body> <p> <img src=i.gif style=position: absolute; top: 0px; left:0px; alt=image</p> <p style=position: absolute; top:50px; left:50px; z-index:3;> Positioned Text</p> </body> </html> Relative: In which elements are positioned relative to other elements. Unlike absolute, relative positioning keeps elements in the general flow of elements on the page, so positioning is relative to other elements in the flow. Element span is grouping element- it does not apply any inherit formatting to its contents. Its primary purpose is to apply CSS rules to its contents. Element span is an inline element- it is displayed in line with other text and with no line breaks. Setting the position property to relative, as lays out the element on the page and offsets the element by the specified top, bottom, left or right values. Ex: html> <head> <title> Style sheets</title> <style type=text/css> span{color:red;font-size:6px;height:1px} .super{position: relative; top:1px} .sub{position: relative; bottom:1px} </style> </head> <body> <p> the text at the end of this sentence<span class=super>is in superscript</span></p> <p> the text at the end of this sentence<span c lass =sub>is in subscript</span></p> </body> </html>

Background: CSS also provides control over the element backgrounds. CSS add background images to documents. The background-image specifies the image URL for the image logo.gif in the format URL. The Background-position property places the image on the screen page. The keywords top, bottom, center, left and right used individually. The background-repeat property controls the tiling of the background image. Tiling places multiple copies of the image next to each other to fill the background. There we set the tiling to repeat to display only one copy of the background image. The background-attachment property is fixed, fixes the image in the position specified by background-position. Scrolling the browser window will not move the image from its position. Ex: html> <head> <title> Style sheets</title> <style type=text/css> body{ background-image: url(logo.gif);background-position: bottom-right; backgroundrepaeat: no-repeat;} </style> </head> <body> <p> this is an example uses the background image, background postion and background attachment styles. </p> </body> </html> Element Dimensions: In addition to positioning elements, CSS rules can specify the actual dimensions of each page element. <html> </head> <head> <body> <title> Style sheets</title> <div style=float: right; mag=rgin:5cm> welcome <style type=text/css> to CSS programming</div> P{ text-align:justify} </body> </style> </html> Text Flow and the Box Model:A browser normally places text and elements on screen in the order in which they appear in XHTML document. With absolute positioning, it is possible to remove elements from normal flow. Floating: It allows you to move an element to one side of screen, other content in document then flows around the floated element. Each block-level element has a box draw around it known as box model. Margin: Specifies the distance between the edge of the element and any other element on the page. Margins for individual sides can be specified by using margin-top, margin-right, margin-left, margin-bottom. Padding: it is the distance between the content inside the element and element border. Padding can be set for each side of the box with padding-top, padding-right, padding-left and padding-bottom.

Clear: a portion of lines can interrupt the flow of text around a floated element by setting the clear property to the same direction as that in which the element is floated-right or left. Border: it lies between the padding space and margin space. We can set three properties-border width, border-color and border-style. Border-width can be set to thin, medium or thick. Border-styles can be set to none, hidden, dotted, dashed, solid, groove, ridge, inset and outset.

Event Handing:
Event model is respond to user action.DHTML with the event model exists so that scripts can respond to user interaction and change the page accordingly. This makes web application move responsive and user friendly. It can reduce server load. DHTML events are: Event attribute Key board events are:Onkeydown Onkeyprocess Event Description Indicates that a key is being pressed down with facus on the elemen t Indicates that a key has been processed & released with focus on the element Indicates that a key is being released with focus on the element When the user initiates help. Indicates that the element has been clicked Occurs when an element losses focus,meaning that the user has activated another element.typically either by clicking the other element or tabbing to it Indicates the press of a mouse button with focus on the element Indicates the release of a mouse button with focus on the element Indicates that them mouse has moves away from an element When a new choice is made in a select element (or)when a text i/p is changed and the element loses focus Allowed elements under standard HTML <applet>,<font>

<applet>,<font>

Onkeyup Onhelp Mouse Events: Onclick Onblur

<applet>,<font>

<Applet>,<font> Q <a>,<area>,<button>, <input>,<label>,<select>,<text area>,<applet>,<table>,<area>

Onmousedown Onmouseup Onmouseout Onchange

<applet>,<font> <applet>,<font> <applet>,<font>,<layer> <input>,<select>,<textarea>

Indicates that the element has received <a>,<area>,<button>,<input>,<select> focus <textarea>,<label> Onload Indicates that the object has finished <body>,<frameset> loading into the browser Onreset Indicates that the form is being <form> reset,possibly by the pressof reset button Onselect Indicates the selection op text by the <input>,<textarea> user Onsubmit Indicates the form is about to be <form> submitted,generally the result of activating a submit button Event onclick:- one of the most common event is onclick.when a specific item with the mouse,the onclick event fires with javascript,we are able to respond to ionclick and other events.

Onfocus

Example for onclick evetn: <html> <head><title> dhtml event model-onclick </title> <script type=javascript></script></head> <body> <p> click on this text ! </p> Output:DHTML Event model-onclick Click on this text Click me Microsft internet Hi again Ok

<input type=button value=clickme onclick=alert (hi again)/> </body> </html>

Here we click the button clickme then alert window alert dialog box will be displayes,with the message hi again. Event onload:The onload event fires whenever an element finishes loading successfully.i.e all of its children are loaded freuently,this event is used in the body element to initiate a script after the page loads into the client Example for onload event:<html> <head><title> dhtml event model-onload </title> <script language=javascript> var secomds=0;var minutes=0;var hours=0; Function starttimer() { Window.setInterval(updateTimer(),1000); //1000millisec=1sec update every 1000millisec } Function updateTimer() { Seconds++; If(seconds==60) { Minutes++; Output:Dhtml event model-onload Seconds=0; } If(minutes==60) { Hours++; Minutes=0; } Sofar.innertext=hours+:+minutes+:+seconds; } </script></head> <body onload=startTimer()> <p>time you have spent viewing this page so far; <A id=soFar style=font-weight:bold>o</a></p> </body> </html>

__

Time yopu have spent viewing the page soFar:0:2:39 Error handling with onerror:-The web is a dynamic medium sometimes a script refers to objects that wxisted at a specified lacation when the script was written,but the location changes at a later time,rendering the script invalid the error dialog presented by the

prevent this dialog box from displaying and to handle errors more elegantly scripts can use the onerror event to execute specialized error handling code. An example program uses the onerror event to laundh a script that writes error messages to the status bar of the browser Example:-Window.status=error:+errtype+online+errLinenum; <html> Return true; <head><title> DHTML event model-onerror</title> } <script language =javascript> </script></head> Window.onerror=handleerror; <body> Function doThis() <input id=mybutton type=button value=clickme { onclick=doThis()/> Alert(hi);//alert misspelled,creates an error </body> } </html> Function handleError(errType,errURL,errLineNum) { Output:DHTML eventmodel onerror

clickme Error:object expected online6 Custom error output Event onmouse move:Event onmousemove fires repeatedly whenever the user moves the mouse over the web page.an example program shows the event to update a coordinate display the position of the mouse in the coordinate system as the object containing the mouse cursor. <html> <head><title>DHTML eventmodelonmousemove</title> <script language=javascript> Function updateMouseCoordinates() { Coordinates.innerText=event.srcElement.tagName+(+ event.offsetX+,+event.offsetY+); Output:DHTML-Event model-onmouseMove Body(330,64) } </script> </head> <body onmousemove=updateMouseCoordinates()> <span id=coordinates>(0,0)</span><br> <img src=apple.jpg style=position:absolute;top:100;left=100></body> </html>

Note: The offset,offset properties of the evetnt object give the location of the mouse cursor relative to the top-left corner of the object on which then event was triggered.

Onmouseover and onmouseout:The more events fires by mouse movements are onmouseover and onmouseout.when the mouse cursor moves over an element,an onmouseover event occurs for that element when the mouse cursor leaves the element.an onmouseout event occurs for that element.

FILTERS AND TRANSITIONS


Introduction: 1) To offer the kinds of dramatic visual effects filters & transitions are used. 2) Variety of effects such as: Transaction between pages with random dissolves and horizontal & vertical blinds Conversion of colored images to gray Letters glow for emphasis Filters: Applying filters to text and images causes changes that are persistent. Transactions: Transactions are temporary; applying this allows you to transfer from one page to another with a pleasant visual effects such as random dissolve.

1)

Flip Filters: Flipv and fliph: These filters are mirror text or images vertically and horizontally. <style=filter:fliph>Text <style=filter:flipv>Text <style=filter:flipv fliph>Text Output:

Fliph: flips the objects horizontally.

Flipv: flips the objects vertically. 2) Chroma filter: The chroma filter applies transparency effects dynamically, without using a graphics editor to hard code transparency into the image. <style=filter:chroma> Creating Image Masks: Applying the mask filter to an image allows you to create an image mask, in which the background of an element is transparent to the image or color behind it. <style = filter:msk(color=#CCFFFF)> <h1> This is a masked text </h1> Output: 3)

4)

Miscellaneous Image Filter: Invert, gray and x-ray: Invert: Applies the negative image effects. i.e. , dark color to light and light color to dark. <style =filter:invert> Gray filter: Applies a gray scale image. <style = filter:gray> X-ray filter: Inversion of grayscale effect. <style =filter:ray> Output:

5)

Adding shadows to text: Creates a shadowing effect that gives the text a 3-D appearance. <style=filter:shadow(direction=0,color=red)> Direction of the shadow filter determines in which direction the shadow effect is applied. We have 8 directions: 0 up 45 above right 90 right 135 below right 180 below 225 below left 270 left 315 above left

Output:

6)

Creating Gradients with Alpha: This is used for transparency effects which are not achievable with the chroma filler. <style = filter:alpha(style=2, opacity=100, finishopacitu=0)>

Style :determines in whatstyle the opacily is applied. Values: 0 Uniform opacity 1 Linear gradient 2 Circular gradient 3 Rectangular gradient Opacity & finishopacity properties are both percentages that determine at what percent opacity the specified dradient startes & finishes. 7) Making Text Glow: The glow filter adds an area of color arround text. <style = filter:glow(color=red, sterngth=5)> Output:

Glowing text
8) Creating Motion with blur: Creates a illusion of motion by blurring text or images in a certain direction. We have 8 directions as specified in the Shadow filler. <style=filler:blur(add=0, directio45, strengt=0)> Add: adds a copy of original image over a blurring image. Output:

9)

Using the wave Filter: Allows to apply sine-wave distortion to text & images. <style=filter:wave(add=0, fre1, phase=0, strength=10)> Output:

10)

Freq: determines the frequency of wave applied. i.e. , how many complete sine-waves are applied. Phase: indicates the phase shift of the wave. Strength: amplitude of the sine-wave that is applied. Advanced fillers:

Dropshadow and light: Dropshadow: Applies the effect similar to the drop shadow as in photoshop. It creates a blacked-out version of the image and places it behind the image, offset by a specified no. of pixels. Light: Allowsto simulate the effects of a light source shining on your page. This filter used with dazzling results. <style=filter:dropshadow(offx=0, offyz=0, color=black) light()> Offx & offy : Determin by how many pixels the dropshadow is offset. No parameters in light() will be set by scripting. Transition I: Filter blenTrans: blendTrans transition creates a smooth fade-in/fade-out effect. <style= filter:blendTrans (duration=3)> Duration: determines how long the transaction takes. Output :

Some fading text


[original]

Some fading text


[blendTrans]

Transaction II : Filter revealTrans: This filter allows the transition by using professional style transition, from box out to random dissolve. We have 24 types of transitions: 1. Box In 13. Random dissolve 2. Box Out 14. Split Vertical In 3. Circle In 15. Split Vertical Out 4. Circle Out 16. Split Horizontal In 5. Wipe Up 17. Split Horizontal Out 6. Wipe Down 18. Strips Left Down 7. Wipe Right 19. Strips Left up 8. Wipe Left 20. Strips Right Down 9. Vertical Blinds 21. Strips Right Up 10. Horizontal Blinds 22. Random Bars Horizontal 11. Checkerboard Blinds 23. Random Bars Vertical 12. Checkerboard Down 24. Random

TABLES
Tables let us display information in a clear and concise fashion. The block element table oranizes and presents information in neatly aligned rows and coloumns. It is often used to, 1. Present tabular data 2. Layout webpages by aligning content and graphics in horizpntal and vertical grids to achieve visual communication dsigns. 3. Organize entities in fill-out forms for user i/p. A table involve many aspects : rows, colums, datacells, headings, lines separatings cells, a caption, spacing within and among cells, and vertical and horizontal alignments of cell contents. The rows and columns can be seperated into groupings. A cell can also span several columns or rows. HTML table basics: A table has a number of rows, each containing the same number of table entries (or cells). The following is a table with two rows, two columns or caption <table border=1> <caption> four seasons</caption> <tr><td>spring</td><td>summer</td></tr> <tr><td>fall</td><td>winter</td></tr> </table> The tr element gives you a table row we have 2 rows in this example. A table cell is either a td or th element. Use th for a cell that contains a header for a column or a row. A td may contain any inline and block elements, including table. The table caption is optional. The border =1 attribute in the table element gives the width of the table border. For more spacing between table cells, set the table cell spacing attribute. <table border=1 cellspacing=10>

Table structure:
Four seasons <caption>four seasons</caption>

Table styles:
Border=0(with out border) cell spacing=10 border=1 cell padding=10 border=1

To give cell contents more breathing room inside cells, set the cell padding attribute. For e.g, <table border=1 cell padding=10>

Cell content alignments:


Content in a cell is left aligned horizontally or middle aligned vertically inside the space for the cell. The align (horizontal alignment) and valign (vertical alignment) attributes of tr specify content alignment for all cells in a row. Possible values for align are left, right, center, justify. The align or valign attributes can be placed in a td (or) th to control the content alignment for a single cell. E.g.: <th>align="right"</th></tr> <html> <tr> <head> <th> <code> valign="top" </code> </th> <title>Cell content Alignment</title> <td align="left" valign="top"> content </td> </head> <td align="center" valign="top"> content </td> <body> <td align="right" valign="top"> content </td> <table style="background-color:#def" border="1"> </tr> <tr><th></th> </body> <th>align="left"</th> </html> <th>align="center"</th>

Table width and height:


The width or height of a table is automatically computed to accommodate the contents in the table cell. You may also explicitly suggest a width using the width attribute of table. The width and height of each table cell are normally computed automatically to accommodate the cell content. For e.g, <table width=60% border=1>

Row and column span:


A table cell can span multiple rows and columns. Here we use colspan specifies number of columns or rowspan attributes for number of rows. For e. g, </tr> <html> <tr align="center"> <head> <td rowspan="2"> C </td> <title>Table demo</title> <td height="40px">D </td> </head> </tr> <body> </table> <table border="1" width="120"> </body> <tr align="center"> </html> <td colspan="2" height="40px">A</td> <td rowspan="2" >B</td>

Output:

Row and column spans In above example, cell A which spans 2 columns and cell B which spans 2 rows and cell C spans 2 rows NESTED TABLES:You can put one table inside another easily. All the complicated formatting and positioning will be done automatically. The below example indicating one row containing two cells: a picture or information these two things are placed in these two cells. The structure of the nested table is: <td><img src="srinivasa.jpg" width="240" <html> height="155"> </td> <head> <td><!--place the nested table here--></td> <title>Table demo</title> </tr> </head> </table> <body> </body> <table frame="box" cellpadding="0"> </html> <tr valign="top">

Output:-

BASIC TABLE TAGS


S.No. TAGS DESCRIPTION ATTRIBUTES align: specifies the horizontal alignment of the table. It can be left,right or center. background: specifies background image for the table. bgcolor: sets the background color for the table. border: sets the border width. bordercolor: sets the external border color. cols: specifies the no. of columns in a table. hight: gives the height of the table width: set the width of the table. cellspacing: for more spacing between table. cellpading: to cell give cell contents more breating room inside cells. 2 3 <tr>....</tr> <th> .. </th> creates row in a table creates a table heading
specifies the data for a table cell specifies the title of a table. creates a table head while grouping rows creates a table body while grouping rows. creates a table foot while grouping rows.

<TABLE></TABLE>

create a table

align,bgcolor, bordercolor, valign<to control content alignment for a single cell). align,bgcolor, bordercolor, background, height, valign, width. align, background, bgcolor, bordercolor, height, valign. width, scope, align, valign. align(l,r,c,t), bgcolor, valign. align, bgcolor, valign align, bgcolor, valign.

4 <td>..</td> <caption>.. 5 </caption> 6 7 8 <thead>..</thead> <tbody>.</tbody> <tfoot>....</tfoot>

ARRAYS
Arrays are data structures consisting of related data items (sometimes called collections of data items). Java script arrays are dynamic entities, in that they can change size after they are created. An array is a group of memory locations that all have some name and normally are of the same type. To refer to a particular location or element in the array and the position number of the particular element in the array. Each element of an array can be referred using an index. Array can store names of all the students in a class. Student[0]=Adam Student[1]=Bryan Student[2]=Calvin

Arrays Declaration:Every array has to be declared before it is used. ArrayName=new Array(arrayLength) Arrayname=new Array() arrayLength is the of an array, which denotes the number of elements that can be stored in the array. First element of an array has an index 0, next element has an index 1 and so on. Student=new array[5]

Arrays Element:Javascript does not place any restrictions on the type of element stored in an array. You can store an integer, string, floating point number, Boolean value, null value and also an array object. MyArray =new Array(1, s2, 12.4, str, true, new Array(1,2,3)) MyArray[0]=1 MyArray[4]=true MyArray[1]=s2 MyArray[5][ 0]=1 MyArray[2]=12.4 MyArray[5][1]=2 MyArray[3]=str MyArray[5][2]=3

Arrays The length property:Since javascript is object based language, arrays have been implanted as objects. Each object is a collection of data and methods, which act upon the data. The method length of an array object returns the size of an array. MyArray length

Array example:<html> <head> <title>simple array example</title> <script language="javascript"> //declaring and allocating array. var arr=new Array(1, "s2", 12.4, true); var n=arr.length;//finding length using length property for(var i=0;i<n;i++) { document.write("arr["+i+"J:"+arr[i]+"<br>"); } </script> </head> </html>

Reference and Reference Parameter:Two ways to puss arguments to function call by value and call by reference. When an argument passed to a function using call by value. A copy of the argument value is made. Call by reference:- This is accomplished by passing to called function the actuallocation in memory, where the data resides.

Call by value
Numbers, Boolean values are passed to function.

Call by reference
All objects, Array values are passed to function.

Passing Arrays to functions:To pass an array argument to a function, specify the name of the array without brackets For example: var arr=new Array[10]; max(arr); In javascript, every array object knows its own size. Thus, when we pass an array object into a function. We do not pass the size of the array.

Example:<html> <head> <title>pass by reference </title> <script language="javascript"> var arr = new Array(10); document.write("Enter 10 elements<br>"); for(var i=0; i<10;i++) { arr(i) = Parse.Int(window.prompt("enter elements","0")); } for(var i=0; i<10;i++) { document.write(arr[i]+"<br>"); } max(arr);//passing array to function function max(arr)//defining max() function. { var m; m=arr[0]; for(var j=1;j<10;j++) { if(m<arr[j]) m=arr[j];

} document.write("max is :"+m+"<br>"); }

</script> </head> </html>

Multiple scripting arrays:Multiple subscripted arrays with two subscripts often are used to represent tables of values consisting of information in rows and columns. To identify a particular table element, we must specify the two subscripts. The first identifies row, Second identifies column Arrays that require two subscripts to identify a particular element are called double subscripted arrays. Javascript does not support multiple subscripted arrays directly. Double subscripted array a1 that contains three rows and four columns.
column 0 row 0 a[0][0] row 1 a[1][0] row2 a[2][0] column 1 a[0][1] a[1][1] a[2][1] column 2 a[0][2] a[1][2] a[2][2] column3 a[0][3] a[1][3] a[2][3]

Example:Var arr = new Array[3]; Arr[0] = new array[5]; Arr[1] = new array[4]; Arr[2] = new array[9];

Example program:<html> <head> <title>2-d array</title> <script> var m=parseInt(window.prompt("Enter no. of rows","0")); //declaring array of 'm' elements. var n=parseInt(window.prompt("Enter no. of columns","0")); for(var i=0;i<m;i++) { //declaring no. of columns for every row. //declaring 'n' columns for 'm' rows. a[i]=new Array[n]; } //storing array values for(var i=0;i<m;i++) { for(var j=0;j<n;j++) { a[i][j]=parseInt(window.prompt("Enter a[][]element","0")); } } document.write("<h3>matrix</h3>"); //printing in matrix form. for(var i=0;i<m;i++) { document.write(a[i].join(" ")); document.write("<br>"); } </script> </head> </html>

Binary search:<html> <head> <title>Binary search</title> <script language="javascript"> var arr=new Array(50); var flag=0; var n=parseInt(window.prompt("Enter no. of elements","0")); //string array element for(var i=0;i<n;i++) { arr[i]=parseInt(window.prompt("Enter elements","0")); } //asking search element var x=parseInt(window.prompt("enter search element","0")); var top=0;bot=n-1;//low and high subscript while(top<=bot && flag==0)//binary search { var mid=(top+bot)/2; if(x>arr[mid]) top=mid+1;//search high end of array if(x<arr[mid]) bot=mid-1;//search low end of array if(x==arr[mid]) flag=1;//match } if(flag==1) document.write("Element found, position i"+mid); if(flag==0) document.write("Element not found"); </script> </head> </html>

Bubble sort:<html> <head> <title>Bubble sort</title> <script language="javascript"> var a=new Array(50); var n=parseInt(window.prompt("Enter no. of elements","0")); //string array element for(var i=0;i<n;i++) { a[i]=parseInt(window.prompt("Enter elements","0")); } document.write("before bubble sort:"); document.write(a.join(" ")); //bubble sort for(var i=0;i<(n-1);i++) { //for all array,comparing to element and its next element comaring element for(var j=0;j<(n-(i+1));j++) { if(a[j]>a[j+1]) { var t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } document.write("<br>after bubble sort"); document.write(a.join(" ")); </script> </head> </html>

Output:-

3.APPLETS
Introduction:
An applet is a java program that is embedded in a html document and run with the help of java enabled browsers such as interneet explorer Unlike java applications applets dont have a main method. All applets inherit the supper class applet. An applet class contains several methods that helps to control the execution of an applet. An applet must import java. Applet and java.awt packages. Applet are event driven i.e. an applet waits until an event occurs. Example:Import java.awt.*; Import java.applet.*; Public class firstapplet extends applet { Public void paint (graphic g) { g.drawString(Hello,10,20); } } How to run the applet: There are two ways to run an applet. 1. Executing an applet within a java complatible web browser. 2. Executing an applet using applet viewer this excutes the applet in a window. To Exectute an applet using web browser we must writea small HTML text file which contains the appropriate Applet tag <applet code=firstApplet width =300 height=100> </applet> After creating the file we can execute our browser and then load this file which makes firstApplet to execute. Example: Import java.applet.*; Import java.awt.*; /* <applet code=first applet width =150 Difference between Application and Applet. Application Applet 1. Applications are stand alone programs 2. main () method exists 3. They need a java interpreter for execution. 4. They have no hard disk accessing restrictions. 5. they doesnt need any secrity 6. they can share any software which is available. 7. using plug ins we can embed latest additions of software. 1. Applets are not stand alone programs. 2. they is no main () method. 3. they need a browser like netscape for execution. 4. they cant access hard disk. 5. they need topmost security for hard disk files. 6. they cant share. 7. we cant use plug-ins directly including browser plugins that are incorporated on the users system.

Public class first applet extends applet { Public void paint(Graphic g) { g.drawString(Hello,20,20); } } In order to execute firstapplet wth an appletviewer we may also execute the html file if suppose the html file is app.html then the following commond will run firstApplet Ex: c:/>appletviewer app.html Life Cycle of an Applet: An applet life cycle consists of various methods let us discuss those methods briefly. 1. init(): this init() is the first method to be called this is where you should initialize variables this method is called only once during the runtime of your applet. Syntax: Public void init() { Code . } 2. start(); the start() is called after init() it is also called to restart an applet after it has been stoped where as init() is called once the first time an applet is loaded start() is called each time an applets HTML document is display on screen. Syntax: Public void start() { Code } 3. Print(): The paint() method is called each time yor applets output must be redrawn paint() is alos called when the applet begins execution the paints() has one parameter of type Graphics this parameter will contain the graphics context which describer the graphics environment in which the applet is running. Syntax: Public void paint(Graphics g) { Code } 4. Stop(): The stop() is called when a web browser leaves the html document containing the applet when it goes to another page you can restart them when start is called if the returns to the page Syntax: Public void stop() { Code }

5. destroy(): the destroy() is called when the environment determines that your applet needs to be removed completely from memory the stop() always called before destroy() method. Syntax: Public void destroy() { Code } Example: An applet life cycle Import java.awt.*; Import java.applet.*; /* <applet code = appletlifecycle width =300 height=100> </applet> */ Public class cppletlifecycle extends applet { // Called first Public void init() { // initialization } /* Called second after init() also called when ever the applet is restarted */ Public void start() { // Start or Resume execution }

// Called when the applet is stopped Public void stop() { //Suspends execution } /* Called when applet is terminated this is the lost method executed */ Public void destrory() { // perform shutdown activities } // Called when an applet window must be restored Public void paint(Graphics g) { // redisplay contents of window } }

Types of Applets:
There are two different types of applets. They are: 1. Applets that are based directly an Applet Class 2. Applets that are based Swing class JApplet 1. Applets that are based directly on applet class This type of applet make use of the abstract window toolkit (AWT) in order to provide the graphical usesr interface. 2. Applet that are based on swing class JApplet This type of applets make use of the swig classes in order to providde the graphical user interface Applet display methods: The different methods used in the applet are give below. 1. drawstring() 2. setbackground() 3. setForeground() 4. ShowStatus()

1. drawstring(): Applet uses drawstring() to display messages in applet window. Which is a member of graphics class typically it is called from within paint() Syntax: Void draw String (String message, int x, int y) Here message is the string to be outut beginning at x,y in a java window the upper left comer is location 0,0 2. setbackground(): this method is used to set the background color of an applets window Syntax : void setBackground(Color new Color) 3. SetForeground: To set the foreground color (The color in which text is shown) Syntax: Void setForeground(Color newColor) Here newColor specifies the new color the class color defines the constands shown here Color.black color.magneta Color.Blue Color.Orange Color.cyan color.pink Color.darkgray Color.red Color.gray Color.white. 4. showstatus(): In addition to displaying information in its window, an applet can also output a message to the status window of the browser or appletviewr an which it is running the status window is a good place to give the user feed back about what is accruing in the applet. Syntax: Void showstatus(Sting msg) Example: SetBackground(Color.pink); Import java.awt.*; SetForeground(Color.green); Import java.applet.*; } /* <applet code=displaymethods width = 200, height=70> Public void paint(Graphics g) </applet> */ { Public class displaymethod extends applet g.drawstring(this is the applet window,20,30); { Show Status(this is the status window); Public void init() } { }

HTML APPLET TAG :


Many attributes are included in the <applet> tag through some attributes are mandatory majority are otional. The syntax for a fullerform of the applet tag is shown here. < Applet [ CODEBASE = Codebase URL] Code = AppletFile [ Alt = atternate Text ] [Name = applet Instane Name] Width = pixels Height = pixels [ Align = alignment] [ vspace= pixels] [ HSPACE = pixels] [ <param name = attribute name value = attributevalue>]

[<param name = Attribute Name2 Value = Attribute Value] [ HTML display in the absence of java] </Applet> Code Base : Code base is an optional attribute that specifies the base URL of the applet code which is the directory that will be searched for the applets executable class file. Code : Code is a required attribute that gives the name of the file containing your applets eampile class file this file is relative to the codebase of the applet. ALT : The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognige that should be displayed if the browser recognizes the Applet tag but connot currectly run java applets. Name : Name Is an optional attribute used to specify a name for the applet instance to obtain an applet by name use get applet() which is defined by applet context interface. Width and height: Width and height are required attributes that give the size (in pixels) of the applet display area. Align : Align is an optional attribute that specifies the alignment of the applet the possible values are left, right, top, bottom , middle, texttop and baseline.

Vspace and hspace: These attributes are optional vspace specifies the space in pixels above and below the applet hspace specifies the space in pixels an each side of the applet.

PARAM NAME AND VALUE:


The param tag allows you to specify applet specific arguments in a html page applets access their attributes with the get parameter() method. Passing parameter to applets: The applet tag in html allows you to pas parameters to your applet to retrieve a parameter use the get paramenter() method it returns the value of the specifed parameter in the form of a string object thus for numeric and Boolean values you will need to convert thir string representations into their internal formats. Ex: // use parameters : Import java.awt.*; Boolean active; Import java.applet.*; // initialize the string to be displayed . /* Public void start() <applet code= parademo width = 300 height = 80 > { <param name = fontName value = Courier> String param; <param name = fontsize value = M> Font name = get parameter(font Name); <param name = leading value = 2> If (font name == null) <param name = account Enabled value = true> Font name = not found; </applet> Param = getparameter (fontsize); */ Try Public class paramDemo Extends Applet { { If (param! = null) // if not found String font Name; FontSize = Integer.parseInt (Param); Int font size ; Else Float leading; Font size = 0 ;

} Leading = -1; Catch(Number Format Exception e) } { Param = getparameter( account Enabled); Font size = -1; If (param!=null) } Active- Boolean valueof(param).boolean value(); Param = get parameter(leading); } Try Display parameters. { Public void paint (Graphics g) If(param ! = null)// if not found { Loading = float.vlaue of (param) : float value()); g.drawString (font name: + fontName, 0,10); Else g.drawString(font size:+ fontsize,0,26); Leading = 0 ; g.drawString(leading +leading,0,42); } g.drawstring(Account Active : +Active,0,58); Catch(numberFormat Exception e) } { } An abstract window toolkit container is called a component In gui in use interaction with the system is through components components are also known as widgets. AWT Architecture : The components generated in AWT are platform depent i.e. the components react to the native environment for example a button will have a different look on windows machine and macitosh machine but java is made portable event with awt by using lowest common denominator architecture this architecture insures that compontes exist on every aparating system that support GUI environment. Event : An action performed by the user through a componet is called an event Example of actions that generate events include clicking a mouse pushing a button etc. Componet : Componets are used by the user to interact with this user interface thse componets are added to a container where container is alos a component Example : Button , textfield, lable etc. Panel : panel is alos container with out a tittlebar , menubar or any outlines so it does not have a physical appearance. This is the reson which makes it indepent and always work under window or an applet and i.e. it cont be a toplevel window. As a container it holds the components and as a componet it can be added to the other container. Frame: Both frame and applet contains borders so they can be used as an tpo level window . They are visible to the user only when the componets are added to them. Frame is a subclass of window and has a tittle bar borders and resizing corners. There are two constructiors of frame window they are Frames () Frame(String title) There are many methods to work with frames they are set size(): this method is used to set the dimensions of a window. Container : A container is a subclass of copoet class it contains all the componets example window, frame, applet panel etc are all containers. GetSize() : this method is used to get the current size of the window. Getvisible(): we can make a window visible by calleing this method. SetTitle(): this method is used to set or change the tittle of a window.

Window: Window class creates top level window which is not contained in any other container It is visible directly on the desktop A window is a container for information it can be used to display outputs drawing etc. Status windows is a good place for the user to give information about applets. It is also useful for displaying errors , suggestions. Canvas: A canvas is a user interface componet, which can be used to draw graphics and enable user interaction. When we create and display convas object it appears as a blank space inside the container. Ex: Canvas s= new canvas(); s.setsize(100,100); s.setBackground(Color.red) add(s); Event handling: Event is an action performed by the user . These actions can be pressing a key moving mouse clicking mouse pushing buttons etc. When such an action is performed then an event is generated such events should be handled. The process of handling events is called event handling. There is an approach to event handling called delegation event model. Delegation Event Model: The moderen approach to handling events is based on the delegation even model which defines standard and consistent even model which defines standard and consistent mechanisms to generated and process events. Its concepts is quirte simple a source generates an event and sends it to one or more listeners. In this scheme the listener simply waits until it receives an event. Onece an event is received the listener process the event and then returns. In this model, listeners must register with a source for receiving an event notification. The advantage of this notifications are sent only to those listeners which are interested in resceving them. Note : java also allows you to process events with out using the delegation model this can be done by extending an AWT componet. Events: 1. An Event is an object the describes a state change In a source . 2. Events are generated when the user interacts with the elements in a graphical user interface. 3. some of the actions that generate events are pressing a button entering the data via keyboard selecting an item in a list clicking the mouse etc 4. events may also be generated with interacting with user interfaces for example an event may be genteraed when the time expires a counter reaches a values, etc. Event Listeners: 1. A listener is an object which is notified whne an event occurs. 2. it must register with sources for receiving and processing those notification. 3. the methods are defined in a set of interfaces found in java.awt, event. 4. interface is a special case of an abstract class in which all methods are abstract. 5. the interface specifies only what to do but not how to do. 6. event listener is a interface which is intended to listen to the occurance of specific event. 7. the event listenr interface implements event listener interface method to respond in an appropriate way for the event generated.

Event Sources : 1. A source is an object that generates an event . 2. this occurs when the internal state of the object changes in some way the event sources may generate more than one type of event. 3. a source must register listeners in order for the listerners to receive notifications about a specific type of event. 4. each type of event hase its own registration method here is the general form. 5. here type is name of the event and el is the reference to the event listner. 6. for example the method that registered a mouse motion listerner is called addMouseMotionListerner(). 7. when an event accurs all registered listeness are notified and receive a copy of the event object this is known as multicasting the event 8. some sources may allow only one listener to register that is known as unicasting the event. Interface Descriplion Actionlistenel Defines one method 10 receive action eventer method. Void action performed (ActionEvent ae) Adjestmentlistee Define one method to receive adjustment events. Method : void adjustment value chaged (Adjestment Event ae) Component listener Defines 4 methods to recognize when a component is hidden resized or shown. Method: Void componeet Reseized (ComponentEvent ce) Void component Mould (componentEvent ce) Void componentHidden(componentEvent ce) Void ComponentShown(Component Event ce) Comtaines Listence Defines two methods to recognize when a component is added to or remove from a contains. From a containe Mehtod: Void componentAdded (ContaineEvent ce) Void Component Removed(Containe Event ce) FocusListene Define 2 methods to recognize when a component gains or loses keyword focus. Methods Void focusGained (FocusEvent fe) Void FocusLost(FocusEvent fe) ItemListenes Defines one method to recognize when the state of an item change Method: Void itemstateChagned(ItemEvent ie) KeyListence Defines 3 methodss to recognize when a key is pressed released or typed Method: Void keypressed(KeyEvent ke) Void KeyReleased(KeyEvent ke) Void Keytyped(KeyEvent ke) Mouselistenes Defines five methods to recognized when the mouse is clicked, enters a component exits a component, is pressed or is relased Methods: Void mouseClicked(mouseEvent me) Void mouseEntered(MouseEvent me) Void mouseExited (MouseEvent me) Void mousePressed(MouseEvent me) Void mouseReleased(MouseEvent me) Defines 2 methods to recognized when mouse is dragged or moved. Method: Void mouseDragged(mouseEvent me) Void mouseMoved(MouseEvent me)

Mouse motion listence

MouseWheel listenet

TextListence

WindowFoculistene

WindowListence

Defines one method to recognize when the mouse wheel is moved. Method: Void mouse wheel moved(Mouse wheelEvent mwe) Defines one method to recognize when a text value changed. Method Void text (Changed (TextEvent te) Define two methods to recognize when a window gains or loses input focus Method: Void windowGainedFocus(WindowEvnet we) Void window LostFocus(WindowEvent we) Define 7methods to recongnize when a window is activated closed deactivated deiconified, opened or Quit. Methods: Void windowActivated(WindowEvent we) Void WindowClosed(WindowEvent we) Void WindowClosing(WindowEvent we) Void window deactivated(WindowEvent we) Void WindowIconified windowEvent we) Void Window opened (WindowEvent we) Description Geneate action event when the button is pressed Generates item event when the check box selected or deselected. Generats item event when the choice is changed. Genenates action events when an item is double clicked gentates item events what an item is selected or deselected. Generates action event when a menu item is selected, geneate item event when a checkable menu item is selected or deselected. Generates adjustment event when the scrollbar is manipulated. Generates text events when the use enters a character Generates window events when a window is activated, closed, deactived, deiconified, iconified, opended or quit

Event sources Source Button Check box Choice List MenuItem Scrollbar Text components Window

Event classes:
Event handling must begin with the event class 1. Event class provide a consistent easy to use menas of encapsulating event. 2. the most widely used events are those defined by the AWT & Swing. Event Object: 1. Event Object is a super class for all event and the roodt of the java event class hierarchy Constrcutor : EventObject(Object sec) Methods: getSource() : Returns the source of the Event Object getSource() ToString() : Returns the string equivalent of the Event Package : Java.util Awt Evnt: The class awtevent defined with in the sove awt package is a subclass of eventtoObject Souper class of all Awt event that are handled by allegation evetn model

Event class Action Event Adjustment Event Component Event Contained Event FocusEvent Input Event ItemEvent keyEvent Mouse wheelEvent Mouse Event Text Event WindowEvent

Desciption Generated when a button is pressed a list item is double clicked or a menu item is selected Generated when a scrool bar is manipulated Generated when a component is hidden moved , resized or become visible Generated when a component is added to or semoved from a containes Generated when a component gains or loses keyboard focus Abstract super class for all component input event classes Genenrated when a check box or list item is clicked also occurs when a choice selection is made or a checkable menu item is selected or deseclted Generated when a input is receired from the keyboard Generated when the mouse wheel is moved Generated when the mouse is dragged moved clicked pressed or released also gentrated when the mouse entrer or exits a componet Generated when the value of a tet area or text field is changed Generated when a window is activeated closed , deactivated , deiconifed, iconified , opened or quit

Constructor: ItemEvent(Itemselected src,int type, object entry, int state) Where , entry the specific item that generated the item event is passed in entry. State current state of an item. Methods Object get item() : to obtain a reference to the item that generated an event. ItemSelectable get item selectable() Int getStateChange() : Return the state change [Selcted or deselected] KeyEvent Class: Go through description part of event class table Constant Key- pressed Key is pressed Key Released Key is Released Key typed character is generated. Note : VK constant specify Virtual key Codes and that are independent of any modifices such as control shift or alt

Swings
Swing : the swing toolket includeds a such set of componets for building GUI and adding interctivty to java application. Swing componets such as JButton JComponet, JFrame, JLabel , Jtree, Jtables etc Swings is part of the java foundation classes the jfc include of the features important to the gui program such as the ability to add rich graphic functionality. Uses mvc (model view controller) architecture Model Represent the data View as a visual seprasentation of data Controller takes input and transulates it to changes in data. Light weight components and pluggable took & feel Platform independent. Japplet class that enables applets to use swing is the Japplet class which extends Applet Japplet is subclass of java.applet.applet.

Japplet provides rich functiohality that is not founding in applet. Eg; japplet support various panes content pane Glass pane root pane Difference between applet & J applet: Applet It is a class of awt package Add () method is used to add components

Japplet it is a class of swing package add() method is used to add content pane

Content pane [ methods] Containe get content pane to obtaine content pane Get content pane Container content pane = get cntent pane (); Add componet to the content pane Content pane . add (comp) First obtain the content pane and them add the component t the container linked to this pane We can also required to invoke remove() & setlayour() methods. We can simples call add() remove() set layour() directly on Japplet J2SE 5 alters these methods so that tyey automenticlal ont the content pane Program { Import java.awt.*; Container content = get content pane (); Import javax.swing.*; Content .setlayout (new flowlayout()); /* <applet code = jappletdemo width =200 height=150> Content.add(new JButton(Button)); </applet> */ Content.add(New Jbutton(Button2)); Public class japplet demo extends japplet } } { Public void init() JFrame: Jframe extend the awt class frame If you are creating an application ratter than an applet tha you will typically use jframe as the top window (with border title & buttons) The componert added to the frame are referred to an contents these are managed by conetn pane Jframe objects store serious objects including a container object known as the contendt pane to and componet to a jframe add it to the cntent pane Features: It a window with title border (optional ) menu bar use specific conmpoent It can be moved, resized , iconified. It is not a subclass of JComponent Deligates responsibility of managing user specified components to a content pane an instance of JPanel. Location of JFrame: Default location- JFrame displayed in the upper left corner of screen Method for specific location Setlocation(Int x,int y) Place upper left corner of a frame at location (x,y) Constructors : Jframe() constructs a new flame that isinitially inneisible. Jfrmae(String title) innisible frame with specified title

Jframe (Graphics configuration ge) Create a frame in the specified gramphic configuration of screen device and the blank title Jframe (string title , graphics configuration ge) Jcomponent : Jcomponent extends the AWT component is container class it is the top level class for all swing components . It provides support for swing pluggable look and feel as well as for many of the enbancements. Jcomponent API I. Void setLocaltion(int x , int y) to position a component in (x,y ) position (measured in mixels) II. Void setLocation(point) in java.awt.componet. Point getLocation() Point getLocation(point) Point getLocationOnScreen() Void setSize (int x int y) Void setSize(Dimension) Dimension getSize() Dimentsion get size(dimension) Program Demo on Jframe & Jcomponent. JButton cancel=new JButton(cancel); Import java.awt.*; Frame.add(cancel); Import javax.swing.*; Frme.setSize(250,250); Public class JFrameDemo Frame.setDefaultClose Operation(JFrame.Extend Close); { Frame.setVisible(true); Public static void main (String a[]) } { } Jframe frame= new Jframe (JFrame Demo); Frame .set Layout (New FlowLayout()); Icon and Labels: Icons: icons are encapsulated by the image icon class , which paints an icon from an image. Constructor: 1. image icon(string filename) 2. image icon(url url) Method: int get Icon Height() -> Return the height of the icon in pixels. Int getIconWidth() ->Return the width of the icon in pixels. Void paint IconCompoent -> paints the icon at position x,y on the graphics context g addition information about the paints operation can be obtained from comp. JLabel : JLabel class extends from JComponent it can display text and or an Icon Constructors : JLabel (Icon i) JLabel(String s) JLabel(String s,Icon I,int align) {align:left,right,center,leading,trailing} S,I are the text and icon used for the label Methods: The label can read and written by following methods Icon getText()

String getText) Void getIcon(Icon i) Icon Void getText(String s) text Eg: Import java.awt.*; Import javax.swing.*; /*<applet code=JLabel Demo width=250 height=150> </applet>*/ Public class JLabelDemo extends JApplet { Public void init() { TextField:

//create an icon ImageIcon i=new ImageIcon(water lilies.jpg); //create a label JLabel jl=new JLabel=new JLabel(lilies,I,JLable.CENTER); //add lable to the content pane Add(jl); }

the swing text field is encapsulated by the JTextComponent class.which extends JComponent. It provides functionality that is common to swing text components. JTextField,which allows you to edit one line of text JTextField is a subclass of TextComponent. Constructors: JTextField() JTextField(int cols) JTextField(String s) JTextField(String s,int cols) String s to be initially presented Int cols:no.of columns in the textfield Buttons: Swing buttons provide special features compared with awt like icons etc.. Swing buttons are subclasses of the AbstractButton class which extends JComponents. Methods: (i.).methods for icons Void getDisableIcon(Icon di) icon is disabled Void getPressedIcon(Icon pi) icon is pressed Void getSelectedIcon(Icon si) icon is selected Void getRollover(Icon ri) displayed when the mouse positioned over that component. (ii.) methods for read and write: String getText) Void getText(String s) text to be associated with Button (iii.) methods for register or unregister a listener. Concreate subclasses of abstraction generate an action events when they are pressed. Void addActionListener(ActionListener al) Void removeActionListener(ActionListener al) JButton class JButton class provides the functionality of a push button. JButton allows an icon a string or both to be associated with the push button. JButoon(Icon i) JButton(String s) JButton(String s,Icon i)

[s for string,I is used for Button] Checkboxes:[we can select more than one option] JCheckBox class,which provides the functionality of a checkbox.is a concreate implementation of AbstractionButton. its immediate superclass is JToggleButton,which provides support for two state buttons. Constructors: JCheckBox(Icon i) JCheckBox(Icon i,Boolean state) JCheckBox(String s) JCheckBox(String s,boolean state) JCheckBox(String s,Icon i) JCheckBox(String s,Icon I,Boolean state) Methods: Void setSelected(boolean state) Is true if checkbox should be checked. when a checkbox is selected or deselected,an ItemEvent is generated this is handled by itemStateChanged(). Radio Buttons:[we can select only one option] Radio button all supported by the JRadioButton class which concreate implementation if AbstractionButton that supporte a group of mutually exclusive buttons. immediate super class is JToggledButton. Constructor: JRadioButton(Icon i) JRadioButton(Icon i,Boolean state) JRadioButton(String s) JRadioButton(String s,Boolean state) JRadioButton(String s,Icon i) JRadioButton(String s,Icon I,Boolean state) Methods: Void add(AbstractButton ab) Is reference to the button to be added to the group Note: Radio buttons are must be configured into a group only one of the buttons in that group can be selected a time.[previous selected buttons are deselected] the ButtonGroup class is instantiated to create a button.[it default constructor is invoked for their purpose] ComboBox: combo box is a combination of a text filed and a drop down list,through the JComboBox class,which extends JComponent combobox normally displays one enrty we can select option or item from drop down list. Constructor: JComboBox() JComboBox(vector v) Initializes the combobox Methods: Void addItem(object obj) To be added to the combo box

Tabbed panes: A tabbedpane is a component that appear as a group of folders in a file cabinet each folder has a title. tabbed panes are commonly used for setting configuration options Tabbed panes are encapsulated by JTabbed Pane class ,which is extends JComponent Tabbed panes are added by calling addTabes Void addTabString s,component c) Program:JTabbedPane tab=new JTabbedPane(); Import java.awt.*; Frame.add(tab,BorderLayout.CENTER) Import javax.swing.*; JButton button1=new JButton(B1); Public class createTabbedPane Tab.add(tab1,button1); { JButton button2=new JButton(B2); Public static void main(String args[]) Tab.add(tab2,button2); { Frame.setSize(400,350); JFrame frame=new JFrame(TabbedPane); Frame.setVisible(true); Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO SE); } //create tabbed pane } ScrollPane: A scrollpane is a component that present a rectangular area in which a component may be viewed horizontal or vertical scrollbars may be provided if necessary In swings there are implementd by JScrollPnae class,which extends JComponent. Constructors: JScrollPane(Component c) JScrollPane(int vsb,int hsb) JScrollPane(Component c,int vsb,int hsb) Constants: HORIZONTAL_SCROLLBAR_ALWAYS always provides horizonatal scroll bars HORIZONTAL_SCROLLBAR_AS_NEEDED provides horizonatal scrollbar,if needed HORIZONTAL_SCROLLBAR_NEVER donot provide horizontal scrollbars VERTICAL_SCROLLBAR_ALWAYS always provides vertical scrollbar VERTICAL_SCROLLBAR_AS_NEEDED provide vertical scroll bar if needed. VERTICAL_SCROLLBAR_NEVER do not provide vertical scroll bar Program: JLabel ll=new JLabel(iicon) Import java.awt.*; JScrollPane scroll=new JScrollPane(); Import javax.swing.*; Scroll.setViewPortView(ll); Public class scrollDemo Frame.getContentPnae().add(Scroll,BorderLayout.CENT { ER); Public static void main(String args[]) Frame.setSize(400,400); { Frame.setVisible(true); JFrame frame=new JFrame(ScrollPane); } Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO } SE); Icon iicon=new ImageIcon(water lilies.jpg);

Program,:
import java.awt.*; import javax.swing.*; /*<applet code=appletdemo width=200 height=150> </applet> Public class appletdemo extends JApplet { Public void init() { Container content=getContentPane(); Content.setLayout(new FlowLayput()); Content.add(new.JButton(Button1)); Content.add(new JButton(Button2); } }

swing component Jcomponent Jbutton JCheckBox JtextField Jframe

description -The root class for all swing components, excluding top-level contines. -A "push" Button corresponds to the Button class in the AWT package. -An item that can be selected or deselected by the user.Correspoindings to the checkbox class in the AWT package. -Allows for editing of a single-line text. Corresponds to the "TextField" class in AWT package. -Extends and corresponding to the "Frame" class in the AWT package but the two are slightly incompatable in terms of adding components to this container. Need to get the current content pane before adding a component. -Extends "Jcomponent". A simple container class but not top-level corresponds to panel class in the AWT package. -Extends and corresponds to the "applet" class in the AWT package also slightly incompatable with the Applet class in terms of adding components to their container. -Extends "Jcomponent" class provides an easy way of displaying pop-up dialog box. -Extends and corresponding to the "Dialog' class in the AWT package. Usually used to inform the use of something or prompt the user for an input. AWT SWING Def: The swing Tool kit includes a rich set of components for building GUIs and adding interactivity to java applications.

Jpanel Japplet JoptionPane Jdialog

Def: AWT is "Abstract" window tool kit". AWT provides a standard API(application programing interface) for writing GUIs in java components. Heavy weight components. Because they require a native os objects to implement their functioinality (i.e., platform dependent) It will invoke native methots. AWT look and feel depends upon the platform AWT include less components than swings. Its allocated nearly resources and waste of resources AWT components are multi-threaded safe. AWT as it user native libraries. AWT component are Button, Label, checkBoxes etc.,

It is more powerfull altermnative for AWT. Light weight components. Because they don't require native os objects (i.e., platform independent) It doesnot invoke native methods. Swing is based on MVC architecture (model view controler) and that ways its look and feel, is independent of hardware and os Swing includes more components than AWT like tree,table It has many features to allocates resources properly. swing component are not designed to be thread safe. The main reason is to gain performance. swing components have been written completely in Java language. Swing components are rich set of components are like Jbutton, Jlabel, JcheckBox and AWT. And automatically get double buffered and get repainted faster.

JTable: A table is a component that displays rows & columns of data. JTable (object data[][], object colhead[]) Here data is a two-dimensional array of the information to be presented, and colhead is a one-dimensional array with the column heading. Program: {1f002, santosh, mca}, Import java.awt.*; {1foo3, Anusha, mca} Import javax.swing.*; }; /*<applet code=JTableDemo width=300 height=400> //create table </applet>*/ JTable table=new JTable(data,colHeads); Public class JTableDemo extends JAPPLET //Add table to scroll pane { Int v = scrollpaneConstants.VERTICAL-SCROLLBAR-ASPublic void init() NEEDED; { Int h = scrollpaneConstants.HORIZONTAL-SCROLLBAR//get content pane AS-NEEDED; Container contentpane=getContentpane(); JScrollpane jsp=new JScrollpane(table,v,h); //set layout //add scroll pane to the constant pane Contentpane.setlayout(new BorderLAyout()); Constantpane.add(jsp,borderlayout.CENTER); //initialize column headings } Final string[] colhead={SNO, SNAME, course} } //initialize data Final object[][] data={ {1f001, kumar, mca}, Note: Table are implanted by JTable class which extends Jcomponent. Trees: A tree is a component that presents a hierarchical view of data. A user has ability to expend or collapse individual sub-trees. Which is extends JComponent. Constractors: JTree(Hashtable<?,?>ht) hash table ht is a child node. JTree(object obj[]) each element of array is child node. JTree(Treenode +n) Root node of tree. JTree(Vector <?> V) each element of vector is child node. Methods: A JTree object generates events when a node is expanded or collapsed 1. Void addTree Expression Lintener(Tree Exception Listener tel) 2. Void remove Tree Expression Listener (Tree Expansion Listener tel) 3. Tree path getpathfor Location(int x,int y) At point (x,y) the mouse is clicked. Constructor: For insert & delete child nodes or change the parent node is, Default mutable treenode(object obj) Method: void add(Mutable TreeNode Child) to add child node to te current node. TreePath getpath() The path to the changed node. TreeExpansion Listener providers two methods. Void treeCollapsed(Tree ExpansionEvent tree) subtree is hidden Void tree Expanded(treeExpnsionEvent Tree) subtree become visible.

Button Demo Import java.awt.*; f.adddddd(newButton(red)); Public class ButtonDemo f.add(new Button(blue)); { f.setSize(300,300); Public static void main(String[] a) f.setvisible(true); { } Frame f=new Frame(Button Demo); } f.setLayout(new flowLayout()); Checkbox demo: Import java.awt.*; f.setLayout(New Flow Layout()); Public class checkboxDemo f.add(new checkbox(pick me,true); { f.setsize(300,300); Public static void main(string[] a) f.setvisible(true); { } Frame f=new Frame(check box demo); } Flow Layout Demo: - Frame, Button, List, Checkbox, Label, Text Field For(int i=0;i<a.length;i++) Import java.awt.*; { Public class FlowLayoutDemo List.add(a[i]); { } Public static void main(String[] a) f.add(list); { f.add(new checkbox(pick me,true)); Frame f=new Frame(Flow LayoutDemo); f.add(new Lable(Enter name:)); f.setLayout(new FlowLayout()); f.pack(); f.add(new Button(Red)); f.setvisible(true); f.sdd(new Button(Blue)); } List list=new list();

Demo:
Import java.awt.*; Public class Demo { Public static void main(String[] a) { Frame f=new Frame(Demo on Label & text field); f.setLayout(new flowLayout()); Grid Layout demo: Import java.awt.*; Import java.applet.*; /*<applet code=GridLayoutDemo width=300 height=400> </applet>*/ Public class GridLayoutDemo extends Applet { Public void init() { Set Layout(new GridLayout(4,4)); //set Font(new Font(java, font.BOLD, 24)); f.add(new Label(user name:)); f.add(new TextField(20)); f.pack(); f.setsize(300,300); f.setvisible(true); } } Int k=0; For(int i=0;i<4;i++) { For(int j=0;j<4;j++) { Add(new Button( +k); K++; } } } }

Layout Managers
Layout Manager arranges the components automatically with in a window. A layout manager is also created with each container object. A layout anager is set using setlayout() method. It is not set, then default manager is used. The general form of setLayout() method is shown below. Void SetLayout(Layout Manager obj) 1. Flow Layout Manager:It is the default and the simplest of all layout manager. It says out the components from upper-left corner, left and right and top to bottom, by leaving a small space between each component. When a line fills, then it comes to the next row. It has 3 forms of constructors. i. Flowlayout() creates default layout i.e., components are placed in center with s pixels space between each component. ii. flowLayout(int how) where how specifies the alignment of the component. These alignment are Flow layout.LEFT Flow layout.CENTER Flow layout.RIGHT Flow layout. LEADING Flow layout.TRAILING iii. flow layout(int how, int hor, int ver) specifies the alignment as well as the horizontal and vertical spaces left between the components. 2. Border Layout Manager:It layout components at four different regions i.e., North, South, East and West and one at the center. If a component is not added in any of the region, then other regions occupy this space. The components of North and South region Extended horizontally. The components of East and West region Expand vertically and center region expand and have all remaining space in layout. The border layout manage takes the following forms. Border layout() Border layout(int hor, int var) Where the first form is the default border layout. The second form specifies the space i.e., horizontal and vertical space between the componenets. Border Layout specifies the following constants: Border Layout.CENTER Border Layout.EAST Border Layout.WEST Border Layout.NORTH Border Layout.SOUTH Example: Import javax.swing.*; JButton b4=new Button(WEST); Import java.awt.*; JButton b5=new Button(CENTER); Public class BorderDemo Extends JFrame c.add(b1,NORTH); Public BorderDemo() c.add(b2,SOUTH); { c.add(b3,EAST); Container c= get content pane(); c.add(b4,WEST); Border Layout b1=new borderLayout(); c.add(b5,CENTER); c.getLayout(b1); setTitleBorder Layout Manager); JButton b1=new Button(NORTH); setsize(400,200); JButton b2=new Button(SOUTH); setvisible(true); JButton b3=new Button(EAST); set Default CloseOperation(Jframe.EXIT-ON-CLOSE);

} New BorderDemo(); } Public static void main(string[] argd{}) { } 3. Grid Layout Manager:Grid Layout lays the component in a two dimensional grid comparison of rows and columns. Each grid contains one component .Component Expand their size similar to the border layout components. And every component has the same weight and height. It defines the following constructors. Grid layout() GridLayout (int rows, int columns) GridLayout(int row, it columns, int hor, int ver) The first constructor creates a single column Grid Layout the second form specifies the number of rows and columns of a Grid layout and third form specifies the horizontal and vertical spaces between components. Example:setTitle(Grid Layout Manager); Import java.awt.*; Import javax.swing.* setsize(200,200); Public class Gridsdemo extends JFrame setvisible(true); { set default Close Operaton(Jframe EXIT-ON-CLOSE); Public GridDemo() } { Public static void main(String args[]) Container c=Get Contentpane(); { Grid Layout g=new GridLayout(3,4); New GridSDemo(); c.SetLayout(g); } for(int i=0;i<12;i++) } c.add(new JButton(Button+i)); 4. Card Layout Manager:This Layout Manager is different from all the other Layout manager. This arrange the components in the form of deck of cards, where only the top most is visible. We can place any card from deck at the top using following methods: Void first(container deck) Void last(container deck) Void next(container deck) Void previous(container deck) Void show(container deck, string card name) This is card layout manager has the following constructors: Card layout() CardLayout(int hor, int ver) The first constructor creates default card Layout, and second constructor specifies horizontal and vertical spaces between the components.

4.JAVA BEANS
Java beans are reusable software components for java that can be manipulated visually in a builder tool. Practically, they are classes written in the java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A java bean is a java object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods. A java bean is a software component that has been designed to be reusable in a variety of different environments. There is no restriction on the capability of a bean. It may perform a simple function, such as checking the spelling of a document, or a complex function, such as forecasting the performance of a stock portfolio. A bean may be visible to an end user. One example on this is a button on a graphical user interface. A bean may also be visible to a user. Software to decode a stream of multimedia information in real time is an example of this type of building block. Finally, a bean may design to work autonomously on a users workstation or to work in cooperation with a set of other distributed components. Software to generate a pie chart from a set of data points is an example of a bean that can execute locally. However, a bean that provides real-time price information from a stock or commodities exchange would need to work in cooperation with other distributed software to obtain its data. JavaBean conventions In order to function as a javabean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace and connect JavaBeans. The required conventions are: The class must have a public default constructor (no-argument). This allows easy instantiation within editing and activation frameworks. The class properties must be accessible using get, set, is (used for Boolean properties instead of get) and other methods (so-called accessor methods and mutator methods), following a standard naming-convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors of which include custom editors for various types of properties. The class should be serializable. This allows applications and frameworks to reliably save, store and restore the beans state in a fashion independent of the VM and of the platform. JavaBean example:
public class PersonBean implements java.io.serializable { private String name; private Boolean deceased; /** no-arg constructor(takes no arguments)*/ public PearsonBean() { } public String getName() { return this.name; } public void setName(final String name) { this.name=name; } public Boolean Boolean isDeceased() { return this.deceased; } public void setDeceased(final Boolean deceased) { this.deceased=deceased; } } public class testPersonBean { public static void main(String[] args) { personBean person=new PersonBean(); person.setName(bob); person.setdeceased(false); System.out.printl(person.getName()); System.out.println(person.isDeceased() ? [deceased]:[alive]); } }

Advantages of Java Beans: Software component architecture provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that java technology provides for a component developer: A bean obtains all the benefits of javas write-once, run-anywhere paradigm. The properties, events, and methods of a bean that are exposed to an application builder tool can be controlled. A bean may be designed to operate correctly in different locales, which makes it useful in global markets. Auxiliary software can be provided to help a person configure a bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. The configuration settings of a bean can be saved in persistent storage and restored at a later time. A bean may register to receive events from other objects and can generate events that are sent to other objects. Bean introspection: Introspection is the process of analyzing a bean to determine its capabilities. This is an essential feature of java beans API, because it allows an application builder tool to present information about component to a software designer without introspection, the java beans technology could not operate. There are two ways in which the developer of a bean can indicate which of its properties, events & method should be exposed by an application builder tool. The two methods are: simple naming conventions. Additional class is provided that explicitly supplies this information. (using beaninfo interface). Simple naming conventions: Design patterns for properties: A property is a subset of beans state. The value assigned to the properties determine the behaviour & appearance of that component. 1. Simple 2. Boolean 3. Indexed Simple properties: A simple property has a single value. It can be identified by the following design patterns, where N is the name of the property & T is type. Syntax: Public T getN(); Public void setN(T arg);
Boolean properties: A Boolean property has a value of true or false. It can be identified by the following design, patterns, where N is the name of the property.

Syntax: Public Boolean isN(); Public Boolean getN(); Public void setN(Boolean value); Either the first/second patterns can be used to retrieve the value of a Boolean property. Indexed property: An indexed property contains multiple values. It can be identified by the following design patterns where N is name of the property & T is its type. Syntax:
Public Tgetn(int index); Public void setN(int index,T value); Public T[] getN(); Public void setN(T values[])

Design Patterns for Events:


Beans use the delegation event model. Beans can generate events and send them to other objects. These can be identified by the following design patterns,where T is the type of the event: public void addListener(TListener eventListener); public void addListener(TListener eventListener); throws TooManyListeners; public void removeListener(TListener eventListener); These methods are used by event Listeners to register an interest in events of a specific type. The first pattern indicates that a bean can multicast an event to multiple listeners. The second pattern indicated that a bean can unicast an event to only one listener. The third pattern s used by listener when it no longer wishes to receive a specific type of event notification from a bean. Methods: Design patterns are not used for naming non-property methods. The introspection mechanism finds all of the public method of a bean. Protected & private methods are not presented. Program for a bean using simple naming conventions: { import java.io.*; this.deceased=deceased; import java.io.serializable; } public class PersonBean implements Public Boolean getdeceased() java.io.serializable { { return this.deceased; Private String name; } Private Boolean deceased; Public class TestPersonBean Public PersonBean() { { Public static void main(String[] args) //no argument constructor { } PersonBean p=new PersonBean(); Public void setname(final String name) //creating an object for the class personbean { p.setname(bob); this.name=name; p.setdeceased(false); } System.out.println(p.getdeceased()?[deceased]: Public String getname() [alive]); { } return this.name; } } Public void setDeceased(final Boolean deceased)

Using BeanInfo Interface:


The second approach for introspection is by using BeanInfo interface. This interface defines several methods including, PropertyDescriptor[] get PropertyDescriptor() EventsetDescriptor[] get EventsetDescriptor() MethodDescriptor[] getMethodDescriptor() These returns arrays of objects that provide nformation about propertie,events& methods of the bean. SimpleBeanInfo is a class that provides default implementations of the BeanInfo interface. We can extend this calss & override one or more of them. Program for bean using BeanInfo interface:

import java.awt.*; import java.awt.event.*; import java.io.Serializable; public class colors extends canvas implements Serializable( { Transient private Color color; Private Boolean rectangular; Public colors() { addMouseListener(new MouseAdapter() { Public void MousePressed(mouseEvent me) { Change(); } }); Rectangular=false; Setsize(200,100); Change(); } Public Boolean getRectangular() { return rectangular; } Public void setRectangular(Boolean flag) { this.rectangular=flag; repaint(); } ColorsBeanInfo.java:
import java.beans.*; public class colorsBeanInfo extends SimpleBeanInfo { Public propertyDescriptor[] getpropertyDescriptor() { try { propertyDescriptor rectangular=new propertyDescriptor(rectangular,colors.class);

Public void change() { color=randomColor(); repaint(); } Private colors randomColor() { int r,g,b; r=(int)(255*Math.random()); g=(int)(255*Math.random()); br=(int)(255*Math.random()); return new color(r,g,b); } Public void paint(Graphics g) { Dimension d=getsize(); int h=d.height; int w=d.width; g.setcolor(color); if(rectangular) { g.fillRect(0,0,w-1,h-1); } else { g.filloval(0,0,w-1,h-1); } } }

propertyDescriptor pd[]={rectangular}; return pd; } catch(Exception e) { } } }

Bound properties:
Bound properties tell interested listeners that their value has changed. A bean that has bound property generates an event when the property has changed. For eg: the file name property in file bean is a bound property whwn the file name changes, then imageviewerBean is automatically notified & it loads the new file. To implement a bound property we have to implement to mechanisms. Whenever the value of the property changes , the bean must send a propertychange event to all listeners. This change occur when the set method is called or when the program user carries out an action To enable interested listeners to register themselves, the bean has to implement the following 2 methods.

Void addPropertyChangeListener(PropertyChangeListener) Void removePropertyChangeListener(PropertyChangeListener) The java. beans package has a class called PropertyChangeSupport that manages the listeners. To use the class we must have a data field (object) for the class. Eg: PropertyChangeSupport changeSupport =new propertyChangeSupport(this); We can add/ remove properties to that object, Eg: public void addPropertyChangeListener(PropertyChangeListener listener) { changeSupport.addPropertyChangeListener(listener); } Public void removePropertyChangeListener(propertyChangeListener Listener) { changeSupport.removePropertyChangeListener(Listener); }/*for removing*/ Whenever the value of property changes it uses firePropertyChanges() of propertyChangeSupport object. Other beans that want to be notified when the property value changes must implement the interface propertyChangeListener.the interface contains only one method: Void propertyChange(propertyChangeEvent event) whenever the property value changes the will be invoked.

Constrained properties:
A Constrained properties is Constrained by the fact that any listener can veto proposed changes a bean that has constrained property generates an event when an attempt is made to change its value. The event is of type propertyChangeEvent. It is sent to object as that previously registered an interest in receiving such notification. Those objects have the ability to veto the proposed changes. Anyone can veto the changes by throwing an exception called propertyVetoException To build a constrained property, the bean must have following two methods to manage vetoAbleChangeListener object: a)public void addVetoableChangeListener(VetoableChangeListener Listener); b) public void removeVetoableChangeListener(VetoableChangeListener Listener); the java beans package has a class called vetoableChangeSupport that manages vetoableChangeListener. The bean should contain the object of this class. Private vetoableChangeSupport vetoSupport=new vetoableChangeSupport(this); Adding/removing listeners should be done to this. Eg: Public void addvetoableChangeListener(addvetoableChangeListener Listener) { vetoSupport.addvetoableChangeListener(Listener); //for adding } Public void removevetoableChangeListener(addvetoableChangeListener Listener) { vetoSupport.removevetoableChangeListener(Listener); //for remove } To update constrained property value: Notify all vetoableChangeListeners of the intent to change the property. If none of them throws the exception then update the value of the property. Notify all propertyChangeListeners to confirm that a change has occurred. *Until all the listeners have agreed the value will not be changed. The JavaBeans APIs:

The interfaces defined in java.beans : i. propertyChangeListener: A method defined in this interface is invoked when the property is changed. Syntax: Void propertyChange(propertyChangeEvent event) ii) vetoableChangeListener: Description: the method of this interface is invoked when a constrained property is changed. Syntax: void vetoableChange(propertyChangeEvent event) iii)BeanInfo: Description: This interface allows a designer to specify information about the properties, events and methods of a bean. Methods: getEventDescriptiors() getMethodDescriptiors() getPropertyDescriptiors() getIcon(int iconType) getBeanDescriptiors() iv. Customizer: Description: This interface allows a designer to provide a graphical user interface through which a bean may be interface. Method: setObject(object bean) Syntax: void setObject(object bean)
Interface propertyChangeListener Description When a bound property is changed the method will be invoked When a constrained property is changed the method will be invoked. Gives information about properties, events and methods of a bean. Provides a GUI interface through which a bean may be configured

vetoableChangeListener

BeanInfo customizer

The classes that are defined in java.beans. i)BeanDeccriptor: Description:this class provides information about a bean Syntax : BeanDescriptor(class beanclass, class customizing) Constructs an object for a bean that has customizer. Methods: Class getBeanclass() : returns the class object that defines the bean. Class getcustmizedclass() : returns class object that defines beans customizer. ii) Introspector : Description: This class analyzes a bean and constructs a Beaninfo object that describes the component. Method: Static Beaninfo getBeanInfo(class beanclass) (Gets the beanInfo of given class) iii) Property (changeEvent): Description: This event is generated when bound or constrained properties are changed. It is sent to object that registered an interested in these in interest in these events and implements either propertychangelistener or vetoableChangelistener interface. Methods:

PropertyChangeEvent(object sourcebean, string property name object old value, object new value) ---constructs a new propertyChangeEvent object. Object getvalue() :returns new value of the property. Object getOldvalue():returns previous value of the property. String getPropertyName():returns name of the property. iv) SimpleBeanInfo: Description: this class provides functionality that can be used when writing BeanInfo classes. Methods : Image loadImage(string resourceName) : returns an image object file associated to the resource. propertyDescription: Description:instances of this describes a property of a beam. Methods: PropertyDescriptor: Description : Instanes of this class describes a property of a bean. Methods: propertyDescriptor(string propertyName,class beanclass) class getPropertyType()returns a class object for the property type . method getReadMethodreturns the get method. Boolean isbound() Void setBound(Boolean b) Boolean isConstrained() Void setConstrained(boolean b) v) propertyChangeSuport : Description: Bean that support bound properties can use their class to notify propertyChangeListener object. Methods: propertyChangeSupport(object sourcebean)--constructs an object. Void addPropertyListener(propertyChangeListener listener) Void removepropertyChangeListener(propertyChangeListener listener) vi) vetoableChangeSupport :
Description: beans that support constrained properties can use this to notify vatoableChangeListeners objects. Methods: vetoableChangeSupport (object sourceBean)constructs an object that manages listeners for constrained property change. Void addVetoablechangeListener (vetoableChangeListener listener) Void removeVetoableChangeListener (vetoableChangeListener Listener) vetoableChangeListener[ ] getvetoablechangeListeners ()

Class
BeanDescriptor Introspetor propertyChangeEvent propertyChangeSupport propertyDescriptor simpleBeanInfo vetoableChangeSupport

Description
Provides information about a bean Analyze a bean and constructs a beaninfo object that describes component Support bound properties can use this to notify propertyChangeListener Instances of this class describes a property of a beam Provides functionality that can be used when writing BeanInfo classes Beans that support constrained properties can use this class to notify vetoableChangeListener objects.

BDK (Bean Development Kit)

1. the BDK software can be down loaded from internet 2. it comes in zip file format 3. after installing the BDK software, some default folder gets created names as beans GNU make file & make file are Unix & windows make files ( .gmk & .mk suffixes) for building the demos & the bean box, & for running the bean box Beans / bean box contents 4. Make file for building the bean box 5. Run.sh script for running the bean box 6. A classes directory containing the bean box class files A lib directory containing a bean box support jar file used by makeApplets produced code 7. Sum & sunw directories containing ( automatically generated event adapter source & class files, .ser files & applet files auto) bean box source(.java) files 8. A tmp directory containing automatically generated even adapter source and class files, .ser files and applet files automatically generated by MakeApplet Beans/ demos contains .MK files for building the demo beans An HTML directory containing an applet wrapper demonstration that must be running appletviewer & juggler wrapper A sunm directory containing demo and wrapper. A wrapper directory containing a bean applet wrapper demos directory containing demo source tile. Beans/ doc contains: Demo documentation. A javadoc directory containing javabean and java beans related class and interface documentation. Miscellaneous documentation. Beans/jar contains jar tiles for demo beans. Starting BDK: Open command prompt Change directory to bean Run run.bat file Now you will get following screen. Refer diagram -1 Refer diagram -2 Refer diagram -3 Refer diagram -4 There are four windows that get opened namely tool box, bean box, properties-bean box, method tracer. The bean soft ware, called BDK (Bean development kit), comes with a tool box. We can select the bean from the tool box and drop in the beanbox, modify its appearance and behavior without writing a single code. Builder tools find a beans features ( properties. Methods, events) dynamically by a process known as introspection. Eg:1 Take a juggler bean as an example 1.click the juggler bean from the toolbox,the cursor then changes to cross. 2.click the beanbox window and the juggler bean appears there.we can reposition the bean on the beanbox by moving the mouse over the dashed border.again the cursor get changed while repositioning the bean. 3.now click on the our button bean from toolbox,place it on beanbox.change its label to show 4.repeat step3 for placing one or more ourbutton on the beanbox.change its label to hide.the bean box shown in diagram-5 5.now click on the show button then go to menubar and click on edit ->events->action->action performed Diagram-6

A red line appears,which must be streched to the juggler bean,simply click on the juggler bean Diagram-7 Immediately we will get following event target dialogbox,select show option and then click ok button Diagram-8 We will get message for generating classes as follows: 6.repeat the step5 for another instance of ourbutton bean which is labelled as hide.the only this is that select the target method as hide from the event target dialogbox. Diagram-9,10 Developing a simple bean steps:
1.the name of the bean we create will be named as simplebean.java in the directory of your choice.(classname.java)name of the file and bean name must be same. The following are the details in steps. First write the bean source code Open notepads write the code and save it. Eg: import java.awt.*; Import java.io.*; Public class sample bean extends canvas implements serializable { } 2.compile the bean as follows C:\mca2>javac samplebean.java(javac filename.java) (where c:\mca2 is working directory) This command generates the file samplebean.class 3.create a manifest file .open the notepad and name the file as MANIFEST.ME write the following lines in the file and save: Name:samplebean.class Java-bean:true Manifest-version:1.0 Created-by:1.6.0_03(sun microsystem.inc) 4.create the jar file.the jar file will contain the manifest and the samplebean class file C:\mca2>jar cvfm samplebean.jar manifest.mf samplebean.class Where a)samplebean.jar is the file that will be created with the files compressed;manifest.mf and simplebean.class b)c stands for to create a jar file .//cvfm are jar command options. c)v stands for verbose data to standard output(monitor). d)f stands for achieve file name is specified. e)m stands for manifest file is included. The above command creates a jar file by name samplebean.jar 5.load the jar file onto the toolbox.select the file>load jar menu item this will bring up a file browser or copy the jar file to bens/jar directory.sample bean appear in toolbox window. Drop a samplebean instance into the beanbox.for this click in the toolbox on the word samplebean.the cursor will change to a crosshair(+symbol).move the cursor to any spot with in the beanbox and click.

Anda mungkin juga menyukai