151

Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Embed Size (px)

DESCRIPTION

Java manual

Citation preview

Page 1: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29
Page 2: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

TableofContents

AdvancedJAVALaboratoryManualUnit1

IntroductionPractical1:Writeanappletthatdrawsacircle.Thedimensionoftheappletshouldbe500x300pixels.Thecircleshouldbecenteredintheappletandhavearadiusof100pixels.Displayyournamecenteredinacircle.(USINGDRAWOVAL()method)Practical2:Drawtenredcirclesinaverticalcolumninthecenteroftheapplet.Practical3:Builtanappletthatdisplaysahorizontalrectangleinitscenter.Lettherectanglefillwithcolorfromlefttoright.Practical4:Writeanappletthatdisplaysthepositionofthemouseattheupperleftcorneroftheappletwhenitisdraggedormoved.Drawa10x10pixelrectanglefiledwithblackatthecurrentmouseposition.Practical5:Writeanappletthatcontainsonebutton.Initializethelabelonthebuttonto“start”,whentheuserpressesthebuttonchangethelabelbetweenthesetwovalueseachtimethebuttonispressed.Practical6:Writeanappletthatusesthemouselistener,whichoverridesonlytwomethodswhicharemousePressedandmouseReleased.Exercise:

Unit2IntroductionPractical7:Writeaprogramthathasonlyonebuttonintheframe,clickingonthebuttoncyclesthroughthecolors:red->green->blue->andsoon.Onecolorchangeperclick.(usegetBackGround()methodtogetthecurrentcolor)Practical8:Writeanappletthatcontainsthreecheckboxesand30x30pixelcanvas.Thethreecheckboxesshouldbelabeled“Red”,”Green”,”Blue”.Theselectionofthecheckboxesdeterminesthecolorofthecanvas.Forexample,iftheuserselectsboth“Red”and“Blue”,thecanvasshouldbepurple.Practical9:Createanapplicationthatdisplaysaframewithamenubar.Whenauserselectsanymenuormenuitem,displaythatselectiononatextareainthecenteroftheframePractical10:Writeanappletthatdrawstwosetsofever-decreasingrectanglesoneinoutlineformandonefilledalternatelyinblackandwhite.Exercise:

Unit3IntroductionPractical11:WriteadatabaseapplicationthatusesanyJDBCdriver.Practical12:DevelopaUIthatperformsthefollowingSQLoperations:1)Insert2)Delete3)Update.Practical13:Writeaprogramtopresentasetofchoiceforusertoselectaproduct&displaythepriceofproduct.

Page 3: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Exercise:Unit4

IntroductionPractical14:WriteasimpleservletprogramwhichmaintainsacounterforthenumberoftimesithasbeenaccessedsinceIT’Sloading;initializethecounterusingdeploymentdescriptor.Practical15:Createaformprocessingservletwhichdemonstratesuseofcookies.Practical16:Createaformprocessingservletwhichdemonstratesuseofsessions.

Unit5IntroductionPractical17:WRITEasimpleJSPprogramforuserRegistration&thencontrolwillbetransferitintosecondpage.Practical18:WriteasimpleJSPprogramforuserloginformwithstatic&dynamicdatabase.Practical19:WriteaJSPprogramtodisplaythegradeofastudentbyacceptingthemarksoffivesubjects.

Page 4: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29
Page 5: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

ADVANCEDJAVALABORATORYMANUALByGayatriPatel

Page 6: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

AdvancedJAVALaboratoryManual

Copyright©ReservedbytheAuthor

Page 7: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

AdvancedJAVALaboratoryManual

Unit1

Introduction

Practical1:Writeanappletthatdrawsacircle.Thedimensionoftheappletshouldbe500x300pixels.Thecircleshouldbecenteredintheappletandhavearadiusof100pixels.Displayyournamecenteredinacircle.(USINGDRAWOVAL()method)

Practical2:Drawtenredcirclesinaverticalcolumninthecenteroftheapplet.

Practical3:Builtanappletthatdisplaysahorizontalrectangleinitscenter.Lettherectanglefillwithcolorfromlefttoright.

Practical4:Writeanappletthatdisplaysthepositionofthemouseattheupperleftcorneroftheappletwhenitisdraggedormoved.Drawa10x10pixelrectanglefiledwithblackatthecurrentmouseposition.

Practical5:Writeanappletthatcontainsonebutton.Initializethelabelonthebuttonto“start”,whentheuserpressesthebuttonchangethelabelbetweenthesetwovalueseachtimethebuttonispressed.

Practical6:Writeanappletthatusesthemouselistener,whichoverridesonlytwomethodswhicharemousePressedandmouseReleased.

Exercise:

Unit2

Introduction

Practical7:Writeaprogramthathasonlyonebuttonintheframe,clickingonthebuttoncyclesthroughthecolors:red->green->blue->andsoon.Onecolorchangeperclick.(usegetBackGround()methodtogetthecurrentcolor)

Practical8:Writeanappletthatcontainsthreecheckboxesand30x30pixelcanvas.Thethreecheckboxesshouldbelabeled“Red”,”Green”,”Blue”.Theselectionofthecheckboxesdeterminesthecolorofthecanvas.Forexample,iftheuserselectsboth“Red”and“Blue”,thecanvasshouldbepurple.

Practical9:Createanapplicationthatdisplaysaframewithamenubar.Whenauserselectsanymenuormenuitem,displaythatselectiononatextareainthecenteroftheframe

Practical10:Writeanappletthatdrawstwosetsofever-decreasingrectanglesoneinoutlineformandonefilledalternatelyinblackandwhite.

Exercise:

Unit3

Page 8: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Introduction

Practical11:WriteadatabaseapplicationthatusesanyJDBCdriver.

Practical12:DevelopaUIthatperformsthefollowingSQLoperations:1)Insert2)Delete3)Update.

Practical13:Writeaprogramtopresentasetofchoiceforusertoselectaproduct&displaythepriceofproduct.

Exercise:

Unit4

Introduction

Practical14:WriteasimpleservletprogramwhichmaintainsacounterforthenumberoftimesithasbeenaccessedsinceIT’Sloading;initializethecounterusingdeploymentdescriptor.

Practical15:Createaformprocessingservletwhichdemonstratesuseofcookies.

Practical16:Createaformprocessingservletwhichdemonstratesuseofsessions.

Unit5

Introduction

Practical17:WRITEasimpleJSPprogramforuserRegistration&thencontrolwillbetransferitintosecondpage.

Practical18:WriteasimpleJSPprogramforuserloginformwithstatic&dynamicdatabase.

Practical19:WriteaJSPprogramtodisplaythegradeofastudentbyacceptingthemarksoffivesubjects.

Page 9: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

UNIT1

GENERALOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnaboutApplet.

DevelopanAppletPrograminJAVA

ExecuteanAppletPrograminJAVAusingAppletViewer

ExecuteanAppletinWebBrowser

LearnHowtouseGraphicsClasstodrawShapes.

LEARNINGOUTCOMESExplain&PracticeGraphicDrawingApplicationsusingApplets.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

INTRODUCTION

WhatisanApplet?AccordingtoSun“Anappletisasmallprogramthatisintendednottoberunonits

own,butrathertobeembeddedinsideanotherapplication….TheAppletclassprovidesastandardinterfacebetweenappletsandtheirenvironment.”

Fourdefinitionsofapplet:AsmallapplicationAsecureprogramthatrunsinsideawebbrowserAsubclassofjava.applet.AppletAninstanceofasubclassofjava.applet.Applet

TheAPPLETHTMLTagAppletsareembeddedinwebpagesusingthe<APPLET>and</APPLET>tags.The

<APPLET>tagissimilartothe<IMG>tag.

TheCODEattributeof<APPLET>tagtellsthebrowserwheretolookforthecompiled.classfile.Itisrelativetothelocationofthesourcedocument.TheCODEBASEattributeisaURLthatpointsatthedirectorywherethe.class

Page 10: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

fileis.TheCODEattributeisthenameofthe.classfileitself.ForinstanceifontheHTMLpageoftheprevioussectionyouhadwrittenTheHEIGHTandWIDTHattributesspecifyhowbigarectanglethebrowsershouldsetasidefor theapplet.Thesenumbersarespecified inpixelsandarerequired.

<APPLET

CODE=“TestApplet.class”

CODEBASE=“classes”

WIDTH=200HEIGHT=200>

</APPLET>

thenthebrowserwouldhavetriedtofindTestApplet.class intheclassesdirectoryinthesamedirectoryastheHTMLpagethatincludedtheapplet.Ontheotherhandifyouhadwritten

<APPLET

CODE=”TestApplet.class”

CODEBASE=“http://www.foo.bar.com/classes”

WIDTH=200

HEIGHT=200>

</APPLET>

thenthebrowserwouldtrytoretrievetheappletfromhttp://www.foo.bar.com/classes/TestApplet.classregardlessofwheretheHTMLpagewas.

In short the appletviewerwill try to retrieve the applet from theURLgivenby theformula(CODEBASE+“/”+code).Once thisURLis formedall theusual rulesaboutrelativeandabsoluteURLsapply.

You can leave off the .class extension and just use the class name in the CODEattribute.Forexample,

<APPLETCODE=“TestApplet”

CODEBASE=“http://www.foo.bar.com/classes”

WIDTH=200

HEIGHT=200>

</APPLET>

ExecutingAppletusingWebBrowserTestApplet.java

Page 11: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

importjava.applet.*;

importjava.awt.*;

publicclassTestAppletextendsApplet{

publicvoidpaint(Graphicsg)

{

g.drawString(“Welcometotheappletworld”,20,40);

}

}

TestApplet.html

<HTML>

<HEAD>

<TITLE>AppletHTMLPage</TITLE>

</HEAD>

<BODY>

<APPLETcode=“TestApplet.class”width=350height=200></APPLET>

</BODY>

</HTML>

The importstatementsdirect theJavacompiler to include the java.applet.Appletandjava.awt.Graphicsclassesinthecompilation.Theimportstatementallowstheseclassestobereferencedinthesourcecodeusingthesimpleclassname(i.e.Applet)insteadofthefullyqualifiedclassname(i.e.java.applet.Applet).

The Applet class provides the framework for the host application to display andcontrol the lifecycle of the applet. TheApplet class is anAbstractWindowing Toolkit(AWT)Component,whichprovides theappletwith thecapability todisplayagraphicaluserinterface(GUI)andrespondtouserevents.

ExecutingAppletdirectlyusingAppletviewerTestApplet.java

importjava.applet.*;

importjava.awt.*;

/*

<APPLETcode=“TestApplet.class”width=350height=200></APPLET>

*/

publicclassTestAppletextendsApplet

Page 12: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

{

publicvoidpaint(Graphicsg)

{

g.drawString(“WelcometoAppletworld”,20,40);

}

}

TheBasicAppletLifeCycle1. ThebrowserreadstheHTMLpageandfindsany<APPLET>tags.2. The browser parses the <APPLET> tag to find the CODE and possibly

CODEBASEattribute.3. Thebrowserdownloadsthe.classfilefortheappletfromtheURLfoundinthe

laststep.4. The browser converts the raw bytes downloaded into a Java class, that is a

java.lang.Classobject.5. Thebrowserinstantiatestheappletclasstoformanappletobject.Thisrequires

theapplettohaveanoargsconstructor.6. Thebrowsercallstheapplet’sinit()method.7. Thebrowsercallstheapplet’sstart()method.8. While the applet is running, the browser passes any events intended for the

applet, e.g. mouse clicks, key presses, etc., to the applet’s handleEvent()method.Updateeventsareusedtotelltheappletthatitneedstorepaintitself.

9. Thebrowsercallstheapplet’sstop()method.10. Thebrowsercallstheapplet’sdestroy()method.

Allappletshavethefollowingfourmethods:

publicvoidinit();

publicvoidstart();

publicvoidstop();

publicvoiddestroy();

SimpleMethodstoDesignApplet

Method Description

void setBackground(Colorcolorname)

To set the background of anappletwindow.

void setForeground(Colorcolorname)

Tosettheforegroundcolorofanappletwindow.

Page 13: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Color getBackground ()

Toobtainthecurrentsettingsforthebackgroundcolor

ColorgetForeground() Toobtainthecurrentsettingsfortheforegroundcolor

Applet getApplet (Stringname)

Toobtaintheappletspecifiedbygiven name from the current appletcontext.

Void showStatus(Stringstatus)

Todisplay the statusmessage inthestatusbarofappletwindow

URLgetDocumentBase()

To obtain the directory of thecurrentbrowserpage.

URLgetCodeBase() To obtain the directory fromwhich the applet’s class file wasloaded

Example:

importjava.applet.*;

importjava.awt.*;

importjava.net.*;

/*

<appletcode=AppletMethodsheight=300width=400>

<paramname=firstvalue=“KDP”>

</applet>

*/

publicclassAppletMethodsextendsApplet

{

Stringarg;

publicvoidstart()

{

arg=getParameter(“first”);

}

publicvoidpaint(Graphicsg)

Page 14: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

{

setBackground(Color.black);

setForeground(Color.white);

URLcodename=getCodeBase();

URLdocname=getDocumentBase();

g.drawString(“String=WelcometoKDP”,30,40);

g.drawString(“ParameterValue=“+arg,30,70);

g.drawString(“Classname=“+codename.toString(),30,100);

g.drawString(“DocumentBase=“+docname.toString(),30,130);

}

}

Output:

PassingParameterstoAppletsParametersarepassedtoappletsinNAME=VALUEpairsin<PARAM>tagsbetween

the opening and closing APPLET tags. Inside the applet, you read the values passedthroughthePARAMtagswiththegetParameter()methodofthejava.applet.Appletclass.

<paramname=parameter_namevalue=parameter_value>CompletesyntaxfortheAPPLETtagincludingParamTag

<APPLETCODEBASE=codebaseURLCODE=appletFileALT=alternateText

Page 15: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

NAME=appletInstanceNameWIDTH=pixelsHEIGHT=pixelsALIGN=alignment><PARAMNAME=appletAttribute1VALUE=value><PARAMNAME=appletAttribute2VALUE=value>

…alternateHTML</APPLET>

ExampleAppletwithparameters

/*

*AppletWithPara.java

*

*/

importjava.applet.*;

importjava.awt.*;

/*

<appletcode=AppletWithParawidth=200height=150>

<paramname=authorvalue=“J.B.Patel”>

<paramname=agevalue=“27”>

<paramname=designationvalue=“Lecturer”>

<paramname=institutevalue=“SSPCVisnagar”>

</applet>

*/

publicclassAppletWithParaextendsjava.applet.Applet

{

publicvoidpaint(Graphicsgp)

{

Stringau=getParameter(“author”);

Stringag=getParameter(“age”);

Page 16: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Stringdesg=getParameter(“designation”);

Stringinst=getParameter(“institute”);

gp.drawString(“Author:”+au,20,40);

gp.drawString(“Age:”+ag,20,70);

gp.drawString(“Designation:”+desg,20,100);

gp.drawString(“Institute:”+inst,20,130);

showStatus(“Parametermethods”);

}

}

Output:

TheCoordinateSystemJava uses the standard, two-dimensional, computer graphics coordinate system. The

firstvisiblepixelintheupperleft-handcorneroftheappletcanvasis(0,0).Coordinatesincreasetotherightanddown.

Page 17: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

GraphicsObjectsInJavaalldrawingtakesplaceviaaGraphicsobject.Thisisaninstanceoftheclass

java.awt.Graphics. Initially the Graphics object you use will be the one passed as anargumenttoanapplet’spaint()method.

EachGraphicsobjecthasitsowncoordinatesystem,andallthemethodsofGraphicsincluding those for drawing Strings, lines, rectangles, circles, polygons and more.Drawing in Java starts with particularGraphics object. You get access to theGraphicsobject throughthepaint(Graphicsg)methodofyourapplet.Eachdrawmethodcallwilllook like g.drawString(“HelloWorld”, 0, 50) where g is the particular Graphics objectwithwhichyou’redrawing.

CommonlyusedmethodsofGraphicsclassareasfollows:

drawString(Strings,intx,inty) Tooutputastringtoanappletataspecified position. It is called fromwithinupdate()orpaint().

drawChars(charc[],intstart_index,intnum_of_char,intx,inty)

To output characters of array toanappletatspecifiedlocation.

drawChars(bytec[],intstart_index,intnum_of_char,intx,inty)

To output characters of byte’sarray to an applet at specifiedlocation.

drawLine(intx1,inty1,intx2,inty2); To draw a line at specificlocation.

drawOval ( int x, int y, int width, int To draw an oval at specified

Page 18: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

height) location x,y having specific heightandwidth

setColor(Colorc) Tosetthecoloroftheobject

fillOval(intx,inty,intwidth,intheight)

TofillcolorinOval

drawRect ( int x, int y, int width, intheight)

To draw a rectangle at specificlocation

fillRect(intx,inty,intwidth,intheight)

Tofillcolorinrectangle

drawArc (int x, int y, int width, intheight,intarcwidth,intarcheight)

TodrawanArc

fillArc(intx,inty,intwidth,intheight,intarcwidth,intarcheight)

TofillcolorinArc.

setFont(Fontf) Tosetthefontf

DrawingLinesDrawingstraightlineswithJavaiseasy.Justcall

g.drawLine(x1,y1,x2,y2)

where(x1,y1)and(x2,y2)aretheendpointsofyourlinesandgistheGraphicsobjectyou’redrawingwith.

Thisprogramdrawsalinediagonallyacrosstheapplet.

importjava.applet.*;

importjava.awt.*;

publicclassSimpleLineextendsApplet{

publicvoidpaint(Graphicsg){

g.drawLine(0,0,this.getSize().width,this.getSize().height);

Page 19: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

}

}

Output

DrawingRectanglesDrawing rectangles is simple.StartwithaGraphicsobjectgandcall itsdrawRect()

method:

publicvoiddrawRect(intx,inty,intwidth,intheight)

As thevariablenamessuggest, the first int is the lefthandsideof the rectangle, thesecondisthetopoftherectangle,thethirdisthewidthandthefourthistheheight.ThisisincontrasttosomeAPIswherethefoursidesoftherectanglearegiven.

ThisusesdrawRect()todrawarectanglearoundthesidesofanapplet.

Page 20: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

importjava.applet.*;

importjava.awt.*;

publicclassRectangleAppletextendsApplet{

publicvoidpaint(Graphicsg){

g.drawRect(0,0,this.getSize().width-1,this.getSize().height-1);

}

}

Output

Remember that getSize().width is thewidth of the applet and getSize().height is itsheight.

WhywastherectangledrawnonlytogetSize().height-1andgetSize().width-1?

Remember that theupper lefthandcornerof theappletstartsat (0,0),notat (1,1).Thismeansthata100by200pixelappletincludesthepointswithxcoordinatesbetween0 and 99, not between 0 and 100. Similarly the y coordinates are between 0 and 199inclusive,not0and200.

FillingRectanglesThedrawRect()methoddrawsanopenrectangle,aboxifyouprefer.Ifyouwantto

drawafilledrectangle,usethefillRect()method.Otherwisethesyntaxisidentical.

This programdraws a filled square in the center of the applet.This requires you toseparatetheappletwidthandheightfromtherectanglewidthandheight.Here’sthecode:

importjava.applet.*;

importjava.awt.*;

Page 21: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

publicclassFillAndCenterextendsApplet{

publicvoidpaint(Graphicsg){

intappletHeight=this.getSize().height;

intappletWidth=this.getSize().width;

intrectHeight=appletHeight/3;

intrectWidth=appletWidth/3;

intrectTop=(appletHeight-rectHeight)/2;

intrectLeft=(appletWidth-rectWidth)/2;

g.fillRect(rectLeft,rectTop,rectWidth-1,rectHeight-1);

}

}

Output

Page 22: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

OvalsandCirclesJava hasmethods to draw outlined and filled ovals.As you’d probably guess these

methodsarecalleddrawOval() and fillOval() respectively.Asyoumightnotguess theytakeidenticalargumentstodrawRect()andfillRect(),i.e.

publicvoiddrawOval(intleft,inttop,intwidth,intheight)

publicvoidfillOval(intleft,inttop,intwidth,intheight)

Insteadof thedimensionsof theoval itself, thedimensionsof thesmallest rectanglewhichcanenclosetheovalarespecified.Theovalisdrawnaslargeasitcanbetotouchtherectangle’sedgesattheircenters.Thispicturemayhelp:

TheargumentstodrawOval()arethesameastheargumentstodrawRect().Thefirstintisthelefthandsideoftheenclosingrectangle,thesecondisthetopoftheenclosingrectangle,thethirdisthewidthandthefourthistheheight.

Example:

importjava.applet.*;

importjava.awt.*;

publicclassBullseyeextendsApplet{

publicvoidpaint(Graphicsg){

intappletHeight=this.getSize().height;

intappletWidth=this.getSize().width;

for(inti=8;i>=0;i—){

if((i%2)==0)g.setColor(Color.red);

elseg.setColor(Color.white);

Page 23: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

//Centertherectangle

intrectHeight=appletHeight*i/8;

intrectWidth=appletWidth*i/8;

intrectLeft=appletWidth/2-i*appletWidth/16;

intrectTop=appletHeight/2-i*appletHeight/16;

g.fillOval(rectLeft,rectTop,rectWidth,rectHeight);

}

}

}

Output

Page 24: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

UsingColorswithAppletsThesyntaxoftheconstructortocreatecustomcolors:

Color(intred,intgreen,intblue);

Example:

newColor(255,100,100);//lightred

Callingaconstructortosetthecolor

Colorc=newColor(255,175,175)

g.setColor(c)

ColorObtained

RedValue

GreenValue

BlueValue

White 255 255 255

Black 0 0 0

LightGray 192 192 192

DarkGray 128 128 128

Red 255 0 0

Green 0 255 0

Blue 0 0 255

Yellow 255 255 0

Purple 255 0 255

TableofRGBvaluesofcommoncolors

You create new colors using the same RGB triples that you use to set backgroundcolorsonwebpages.Howeveryouusedecimalnumbersinsteadofthehexvaluesusedbythe bgcolor tag. For example medium gray is Color(127, 127, 127). Pure white isColor(255,255,255).Pureredis(255,0,0)andsoon.Aswithanyvariableyoushouldgiveyourcolorsdescriptivenames.Forinstance

ColormedGray=newColor(127,127,127);

Page 25: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Colorcream=newColor(255,231,187);

ColorlightGreen=newColor(0,55,0);

Afewofthemostcommoncolorsareavailablebyname.Theseare

Color.black Color.gray Color.orange Color.yellow

Color.blue Color.green Color.pink

Color.cyan Color.lightGray Color.red

Color.darkGray Color.magenta Color.white

TochangecolorsyouchangethecolorofyourGraphicsobject.Theneverythingyoudrawfromthatpointforwardwillbeinthenewcoloruntilyouchangeitagain.

Whenanappletstartsrunningthecolorissettoblackbydefault.Youcanchangethisto red by calling g.setColor(Color.red). You can change it back to black by callingg.setColor(Color.black). The following code fragment shows how you’d draw a pinkStringfollowedbyagreenone:

g.setColor(Color.pink);

g.drawString(“ThisStringispink!”,50,25);

g.setColor(Color.green);

g.drawString(“ThisStringisgreen!”,50,50);

Example:AppletColor.java

importjava.applet.*;

importjava.awt.*;

/*

<appletcode=AppletColorheight=300width=400>

</applet>

*/

publicclassAppletColorextendsApplet

{

publicvoidpaint(Graphicsg)

{

Colorc1=newColor(255,0,255);

Page 26: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Colorc2=newColor(128,128,128);

g.setColor(c1);

intr=c1.getRed();

intgr=c1.getGreen();

intb=c1.getBlue();

g.drawString(“RED=“+r+”GREEN=“+gr+”BLUE=“+b,10,20);

c1=c1.darker();

g.setColor(c1);

g.drawString(“RED=“+r+”GREEN=“+gr+”BLUE=“+b,10,40);

g.setColor(c2);

g.drawString(“RED=“+r+”GREEN=“+gr+”BLUE=“+b,10,60);

c2=c2.brighter();

g.setColor(c2);

g.drawString(“RED=“+r+”GREEN=“+gr+”BLUE=“+b,10,80);

}

}

Output:

FontsYou’vealreadyseenoneexampleofdrawingtextintheHelloWorldAppletprogramof

Page 27: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

thelastchapter.YoucallthedrawString()methodoftheGraphicsobject.Thismethodispassed theStringyouwant todrawaswellasanxandycoordinate. Ifg isaGraphicsobject,thenthesyntaxis

g.drawString(Strings,intx,inty)

The String is simply the text you want to draw. The two integers are the x and ycoordinatesof the lower left-handcornerof theString.TheStringwillbedrawnaboveandtotherightofthispoint.Howeverletterswithdescenderslikeyandpmayhavetheirdescendersdrawnbelowtheline.

Until now all the applets have used the default font, probably some variation ofHelveticathoughthisisplatformdependent.HoweverunlikeHTMLJavadoesallowyoutochooseyourfonts.JavaimplementationsareguaranteedtohaveaseriffontlikeTimesthat canbe accessedwith thename“Serif”, amonospaced font like courier that canbeaccessedwiththename“Mono”,andasansseriffontlikeHelveticathatcanbeaccessedwiththename“SansSerif”.

Thefollowingappletliststhefontsavailableonthesystemit’srunningon.ItdoesthisbyusingthegetFontList()methodfromjava.awt.Toolkit.Thismethodreturnsanarrayofstringscontainingthenamesoftheavailablefonts.Thesemayormaynotbethesameasthe fonts installedonyour system. It’s implementationdependentwhetherornotall thefontsasystemhasareavailabletotheapplet.

importjava.awt.*;

importjava.applet.*;

publicclassFontListextendsApplet{

privateString[]availableFonts;

publicvoidinit(){

Toolkitt=Toolkit.getDefaultToolkit();

availableFonts=t.getFontList();

}

publicvoidpaint(Graphicsg){

for(inti=0;i<availableFonts.length;i++){

Page 28: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

g.drawString(availableFonts[i],5,15*(i+1));

}

}

}

Output

DrawingGraphicsExample:GraphicsDemo.java

importjava.awt.*;

importjava.applet.*;

/*<appletcode=“GraphicsDemo”width=400height=400>

</applet>*/

publicclassGraphicsDemoextendsApplet

{

publicvoidpaint(Graphicsg)

{

setBackground(Color.pink);

setForeground(Color.blue);

Fontf=newFont(“Arial”,Font.ITALIC,10);

Page 29: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

g.setFont(f);

g.drawLine(20,20,50,50);

g.drawString(“Line”,20,70);

g.drawRect(100,20,50,50);

g.drawString(“Rectangle”,100,100);

g.fillRoundRect(200,20,80,50,10,10);

g.drawString(“FilledRoundRect”,200,100);

g.drawOval(20,100,50,80);

g.drawString(“Oval”,25,200);

g.fillOval(100,130,50,50);

g.drawString(“Circle”,110,200);

g.drawString(“WELCOMETOGRAPHICS”,130,350);

}

}

Output:

PRACTICAL1:WRITEANAPPLETTHATDRAWSACIRCLE.THEDIMENSIONOFTHEAPPLETSHOULDBE500X300PIXELS.THECIRCLESHOULDBECENTEREDINTHEAPPLETANDHAVEARADIUSOF100PIXELS.DISPLAYYOURNAMECENTEREDINACIRCLE.(USINGDRAWOVAL()METHOD)SPECIFICOBJECTIVES

Page 30: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Afterperformingthispracticalstudentwillbeableto:

LearnaboutApplet.

DevelopanAppletPrograminJAVA

ExecuteanAppletPrograminJAVAusingAppletViewer

ExecuteanAppletinWebBrowser

LearnHowtouseGraphicsClasstodrawCircle.

LEARNINGOUTCOMESExplain&PracticeGraphicDrawingmethoddrawOval()todrawcircle.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

ENVIRONMENTVARIABLESLIKEJAVA_HOME,PATH,CLASSPATHARECONFIGURED.CODE

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=CenterCircleheight=500width=300>

</applet>

*/

publicclassCenterCircleextendsApplet

{

intw,h;

publicvoidinit()

{

w=getWidth();

h=getHeight();

}

publicvoidpaint(Graphicsg)

{

g.setColor(Color.blue);

g.drawOval((w/2)-50,(h/2)-50,100,100);

g.drawString(“J.B.Patel”,w/2,h/2);

Page 31: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

g.setColor(Color.green);

showStatus(“Thisappletdrawscircleinthecenteroftheapplet”);

}

}

OUTPUT

PRACTICAL2:DRAWTENREDCIRCLESINAVERTICALCOLUMNINTHECENTEROFTHEAPPLET.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAppletPrograminJAVA

ExecuteanAppletPrograminJAVAusingAppletviewerorwebbrowser

LearnHowtouseGraphicsClasstodrawCircle.

LEARNINGOUTCOMESExplain&PracticeGraphicDrawingmethoddrawOval()todrawcirclespatternandsetColor()tofillCircle.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=TenRedheight=500width=300>

</applet>

*/

publicclassTenRedextendsApplet

{

intw,h;

publicvoidinit()

Page 32: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

{

w=getWidth();

h=getHeight();

}

publicvoidpaint(Graphicsg)

{

intcount=0;

g.setColor(Color.red);

for(inti=h;i>0;i=i-50)

{

g.fillOval(w/2-25,h-i,50,50);

count++;

if(count==10)break;

}

}

}

OUTPUT

PRACTICAL 3:BUILTANAPPLETTHATDISPLAYSAHORIZONTALRECTANGLEINITSCENTER.LETTHERECTANGLEFILLWITHCOLORFROMLEFTTORIGHT.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAppletPrograminJAVA

ExecuteanAppletPrograminJAVAusingAppletviewerorwebbrowser

LearnHowtouseGraphicsClasstodrawandfillRectangles.

LEARNINGOUTCOMESExplain&PracticeGraphicDrawingmethoddrawRect()andfillRect()tocreateProgressbar.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

Page 33: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=FillRectGradheight=500width=300>

</applet>

*/

publicclassFillRectGradextendsApplet

{

intw,h,x1=100,x2,y1=50,y2=150,flag=0;

Threadt;

Graphicsg1;

publicvoidinit()

{

w=getWidth();

h=getHeight();

}

publicvoidpaint(Graphicsg)

{

g.setColor(java.awt.Color.red);

g.drawRect(100,50,300,150);

for(x2=100;x2<=300;x2=x2+2)

{

try{

Thread.sleep(1000);

g.fillRect(x1,y1,x2,y2);

}catch(Exceptione)

{}

}

}

Page 34: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

}

OUTPUT

PRACTICAL 4:WRITE AN APPLET THAT DISPLAYS THE POSITION OFTHEMOUSEATTHEUPPERLEFTCORNEROFTHEAPPLETWHEN IT ISDRAGGEDORMOVED.DRAWA10X10PIXELRECTANGLEFILEDWITH

BLACKATTHECURRENTMOUSEPOSITION.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAppletPrograminJAVA

ExecuteanAppletPrograminJAVAusingAppletviewerorwebbrowser

LearnHowtohandleMouseEventsusingMouseListenerandMouseMotionListenersinterfaces.

LEARNINGOUTCOMESExplain&PracticeMouseEventslikeMove,DragandCurrentPositionusinginit(),repaint()methods.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

Page 35: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE

importjava.awt.event.*;

importjava.applet.*;

importjava.awt.*;

/*

<appletcode=MousePositionheight=300width=400>

</applet>

*/

public class MousePosition extends Applet implements MouseListener,MouseMotionListener

{

Strings=””;

intmx=0,my=0;

publicvoidinit()

{

addMouseListener(this);

addMouseMotionListener(this);

}

publicvoidmouseClicked(MouseEventm)

{

}

publicvoidmouseEntered(MouseEventm)

{

}

publicvoidmouseExited(MouseEventm)

{

}

publicvoidmousePressed(MouseEventm)

{

}

Page 36: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

publicvoidmouseReleased(MouseEventm)

{

}

publicvoidmouseDragged(MouseEventm)

{

mx=m.getX();

my=m.getY();

s=“Dragging:”;

repaint();

}

publicvoidmouseMoved(MouseEventm)

{

mx=m.getX();

my=m.getY();

s=“Moving:”;

repaint();

}

publicvoidpaint(Graphicsg)

{

g.drawString(“Mouse”+s+mx+”,”+my,10,10);

g.setColor(Color.red);

g.drawRect(mx,my,10,10);

}

}

OUTPUT:

WhenMoving WhenDragging

PRACTICAL 5: WRITE AN APPLET THAT CONTAINS ONE BUTTON.INITIALIZETHELABELONTHEBUTTONTO“START”,WHENTHEUSERPRESSES THE BUTTON CHANGE THE LABEL BETWEEN THESE TWO

VALUESEACHTIMETHEBUTTONISPRESSED.SPECIFICOBJECTIVES

Page 37: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Afterperformingthispracticalstudentwillbeableto:

DevelopaGUIAppletPrograminJAVAusingAWTButtonControl

ExecuteanAppletPrograminJAVAusingAppletviewerorwebbrowser

LearnHowtohandleAWTButtonEventsusingActionListenerinterfaces.

LEARNINGOUTCOMESExplain&PracticeAWTButtonEventslikeusingactionPerformed()methods.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE

importjava.awt.*;

importjava.applet.*;

importjava.awt.event.*;

importjava.lang.String;

/*<appletcode=ButtonsDemo.classwidth=300height=300></applet>*/

publicclassButtonsDemoextendsjava.applet.AppletimplementsActionListener{

Buttonb1;

publicvoidinit()

{

b1=newButton(“Start”);

add(b1);

b1.addActionListener(this);

}

publicvoidactionPerformed(ActionEvente)

{

if(e.getSource()==b1)

{

Strings;

s=b1.getLabel();

if(s==“Start”)

Page 38: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

b1.setLabel(“Stop”);

else

b1.setLabel(“Start”);

}

}

}

OUTPUT:

When You Press StopButton

When You Press StartButton

PRACTICAL 6:WRITE AN APPLET THAT USES THEMOUSE LISTENER,WHICHOVERRIDESONLYTWOMETHODSWHICHAREMOUSEPRESSEDANDMOUSERELEASED.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAppletPrograminJAVA

ExecuteanAppletPrograminJAVAusingAppletviewerorwebbrowser

LearnHowtohandleMouseEventsusingMouseListenerandMouseMotionListenersinterfaces.

LEARNINGOUTCOMESExplain&PracticeMouseEventslikePressandReleasedusingmousePressed(),mousePressed()methods.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE

importjava.awt.event.*;

importjava.applet.*;

importjava.awt.*;

/*

<appletcode=MouseStateheight=300width=400>

Page 39: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</applet>

*/

public class MouseState extends Applet implements MouseListener,MouseMotionListener

{

Strings=””;

intmx=0,my=0;

publicvoidinit()

{

addMouseListener(this);

addMouseMotionListener(this);

}

publicvoidmouseClicked(MouseEventm){}

publicvoidmouseEntered(MouseEventm){}

publicvoidmouseExited(MouseEventm){}

publicvoidmousePressed(MouseEventm)

{

mx=m.getX();

my=m.getY();

s=”Pressed:”;

repaint();

}

publicvoidmouseReleased(MouseEventm)

{

mx=m.getX();

my=m.getY();

s=”Released:”;

repaint();

}

publicvoidmouseDragged(MouseEventm){}

publicvoidmouseMoved(MouseEventm){}

publicvoidpaint(Graphicsg)

Page 40: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

{

g.drawString(“Mouse”+s+mx+”,”+my,10,10);

g.setColor(Color.red);

g.drawRect(mx,my,10,10);

//g.drawString(“Mousemovingat:“+mx+”,”+my,20,40);

}

}

OUTPUT:

WhenYouPressMouse WhenYouReleaseMouse

EXERCISE:WRITEANAPPLETTHATDISPLAYSASIMPLEMESSAGE:“HELLOAPPLET”.

Code:

Page 41: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

WRITEAJAVAPROGRAMTODRAWLINES,RECTANGLESANDOVALS.

Code:

Page 42: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

Page 43: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

WRITEANAPPLETTHATDRAWSAHUMANFACEWITHARCANDOVAL.

Code:

Page 44: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

TODEVELOPAPROGRAMTOSETTHEGIVENSTRINGINADESIREDFONTANDCOLOR.(FONT:ARIEL,BOLDAND

POINTSIZE20,COLOR:PINK)

Code:

Page 45: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

Page 46: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

UNIT2

GENERALOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnaboutWindowsAWTControls.

DevelopanAWTPrograminJAVA

ExecuteanAWTPrograminJAVA

LearnHowtouseGraphicsClasstodrawShapes.

LEARNINGOUTCOMESExplain&PracticeAWTControlsusingAppletsandFrames.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

INTRODUCTION

AbstractWindowToolkitTheAWTcontainsnumerousclassesandmethodsthatallowustocreateandmanage

windows.AlthoughthemainpurposeoftheAWTistosupportappletwindows,itcanalsobeusedtocreatestand-alonewindowsthatruninaGUIenvironment,suchasWindows.

AWTClassesTheAWT classes are contained in the java.awt package. It is one of Java’s largest

packages. Fortunately, because it is logically organized in a top- down, hierarchicalfashion,itiseasiertounderstandandusethanyoumightatfirstbelieve.

AWTEventEncapsulates AWT events.AWTEventMulticasterDispatches events tomultiplelisteners.

BorderLayoutTheborderlayoutmanager. Border layouts use fivecomponents: North, South, East, West, andCenter.

Page 47: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

ButtonCreatesapushbutton control.CanvasA blank, semantics-freewindow.

CardLayoutThe card layout manager.Card layouts emulate index cards. Only theoneontopisshowing.

CheckboxCreates a check box control.CheckboxGroupCreatesagroupofcheckboxcontrols.CheckboxMenuItemCreatesanon/offmenuitem.

ChoiceCreatesapop-uplist.

ColorManagescolorsinaportable,independentfashion.

ComponentAn abstract super-class for various AWTcomponents.ContainerAsubclassofComponentthatcan

components.

CursorEncapsulates a bitmappedcursor.DialogCreatesadialogwindow.

DimensionSpecifiesthedimensionsofan object. Thewidth is stored inwidth, andtheheightisstoredinheight.

EventEncapsulates events.EventQueueQueuesevents.

FileDialogCreatesawindowfromwhichafilecanbe selected. FlowLayoutTheflowlayoutmanager.Flowlayoutpositions

Page 48: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

components left to right, top to bottom.FontEncapsulatesatypefont.

FontMetricsEncapsulates variousinformation related to a font. Thisinformation helps you display text in awindow.

FrameCreates a standardwindow thathasa titlebar,resizecorners,andamenubar.

GraphicsEncapsulates the graphicscontext. This context is used by the variousoutputmethodstodisplayoutputinawindow.

GraphicsDeviceDescribes agraphics device such as a screen or printer.GraphicsEnvironmentDescribesthecollectionofavailableFontand

GraphicsDeviceobjects.

GridBagConstraintsDefinesvariousconstraints

GridBagLayoutclass.

GridBagLayoutThe grid bag layoutmanager. Grid bag layout displayscomponentssubjecttotheconstraintsspecifiedbyGridBagConstraints.

GridLayoutThegridlayoutmanager.componentsinatwo-dimensionalgrid.

ImageEncapsulatesgraphicalimages.

InsetsEncapsulates the borders of a

Page 49: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

container.LabelCreates a label that displays astring.

ListCreatesalistfromwhich theusercanchoose. SimilartothestandardWindowslistbox.

MediaTrackerManages mediaobjects. MenuCreates a pull-downmenu.MenuBarCreatesamenubar.

MenuComponentAn abstract class implemented byvariousmenuclasses.MenuItemCreatesamenuitem.

MenuShortcutEncapsulates akeyboard shortcutforamenuitem.Panel The simplest concrete subclassofContainer.

PointEncapsulates a Cartesian coordinate pair, storedinx

andy.

PolygonEncapsulates a polygon.PopupMenuEncapsulates a pop-upmenu.

PrintJob An abstract class that represents aprintjob.RectangleEncapsulatesarectangle.

RobotSupports automated testing of AWT- basedapplications.ScrollbarCreatesascrollbarcontrol.

ScrollPaneA container that provideshorizontal and/or vertical scroll bars foranothercomponent.

SystemColorContains the colors of

Page 50: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

GUI widgets such as windows, scroll bars,text,andothers.

TextAreaCreates a multiline editcontrol. TextComponent A superclass forTextAreaandTextField.TextFieldCreates asingle-lineeditcontrol.

ToolkitAbstract class implemented bytheAWT.WindowCreates awindowwithnoframe,nomenubar,

WindowFundamentalsTheAWTdefineswindowsaccordingtoaclasshierarchythataddsfunctionalityand

specificitywitheachlevel.ThetwomostcommonwindowsarethosederivedfromPanel,whichisusedbyapplets,andthosederivedfromFrame,whichcreatesastandardwindow.Muchofthefunctionalityofthesewindowsisderivedfromtheirparentclasses.Thus,adescription of the class hierarchies relating to these two classes is fundamental to theirunderstanding.FigurebelowshowstheclasshierarchyforPanelandFrame.

WorkingwithFrameWindowsAftertheapplet,thetypeofwindowwewillmostoftencreateisderivedfromFrame.

Wewilluseittocreatechildwindowswithinapplets,andtop-levelorchildwindowsforapplications. It creates a standard-style window. Following are two of Frame’sconstructors:

Frame();

Frame(Stringtitle);

Thefirstformcreatesastandardwindowthatdoesnotcontainatitle.Thesecondformcreates a window with the title specified by title. Note that we cannot specify thedimensionsofthewindow.Instead,wemustsetthesizeofthewindowafterithasbeencreated.

CreatingaFrameWindowinanAppletThisexampleoverridestheappletwindow’sstart()andstop()methodssothatthey

showandhidethechildwindow,respectively.Italsocausesthechildwindowtobeshownwhenthebrowserreturnstotheapplet.

SampleFrame.java

/*

Page 51: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<appletcode=“AppletFrame”width=300height=50>

</applet>

*/

classSampleFrameextendsFrame

{

SampleFrame(Stringtitle)

{

super(title);

}

publicvoidpaint(Graphicsg)

{

g.drawString(“Thisisinframewindow”,10,40);

}

}

publicclassAppletFrameextendsApplet

{

Framef;

publicvoidinit()

{

f=newSampleFrame(“AFrameWindow”);

f.setSize(250,250);

f.setVisible(true);

}

publicvoidstart()

{

f.setVisible(true);

}

publicvoidstop()

{

f.setVisible(false);

}

Page 52: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

publicvoidpaint(Graphicsg)

{

g.drawString(“Thisisinappletwindow”,10,20);

}

}

Output:

UsingAWTControls,LayoutManagersandMenusControlsarecomponents thatallowauser to interactwithhisapplication invarious

ways—forexample;acommonlyusedcontrolisthepushbutton.

ControlFundamentals

TheAWTsupportsthefollowingtypesofcontrols:

LabelsPushbuttonsCheckboxesChoicelistsListsScrollbarsTextAreaTextField

ThesecontrolsaresubclassesofComponent.

AddingandRemovingControls

Inordertoincludeacontrolinawindow,wemustaddittothewindow.So,wemustfirstcreateaninstanceofthedesiredcontrolandthenaddittoawindowbycallingadd(),whichisdefinedbyContainer.Theadd()methodhasseveralforms.Thefollowingformistheonethatisusedforthefirstpartofthischapter:

Componentadd(ComponentcompObj)

Here,compObjisaninstanceofthecontrolthatwewanttoadd.Areferenceto

Page 53: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

compObjisreturned.Onceacontrolhasbeenadded,itwillautomaticallybevisiblewheneveritsparentwindowisdisplayed.Sometimeswewillwanttoremoveacontrolfromawindowwhenthecontrolisnolongerneeded.Fordoingthis,callremove().ThismethodisalsodefinedbyContainer.Ithasthisgeneralform:

voidremove(Componentobj)

Here, obj is a reference to the control thatwewant to remove.We can remove allcontrolsbycallingremoveAll().

RespondingtoControls

Except for labels,whicharepassivecontrols,allcontrolsgenerateeventswhen theyareaccessedbytheuser.Forexample,whentheuserclicksonapushbutton,aneventissent that identifies the push button. In general, our program simply implements theappropriateinterfaceandthenregistersaneventlistenerforeachcontrolthatweneedtomonitor.

LabelsLabeldefinesthefollowingconstructors:

Label();

Label(Stringstr);

Label(Stringstr,inthow);

WecansetorchangethetextinalabelbyusingthesetText()method.WecanobtainthecurrentlabelbycallinggetText().Thesemethodsareshownhere:

voidsetText(Stringstr);

StringgetText();

Toobtainthecurrentalignment,callgetAlignment().Themethodsareasfollows:

voidsetAlignment(inthow);

intgetAlignment();

Example:Thefollowingexamplecreatesthreelabelsandaddsthemtoanapplet.

//DemonstrateLabels.LabelDemo.java

importjava.awt.*;importjava.applet.*;

/*

<appletcode=“LabelDemo”width=300height=200>

</applet>

*/

Page 54: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

publicclassLabelDemoextendsApplet

{

publicvoidinit()

{

Labelone=newLabel(“One”);Labeltwo=newLabel(“Two”);Labelthree=newLabel(“Three”);

//addlabelstoappletwindowadd(one);

add(two);

add(three);

}

}

Output:

ButtonsThemostwidelyusedcontrolisthepushbutton.Apushbuttonisacomponentthat

containsalabelandthatgeneratesaneventwhenitispressed.PushbuttonsareobjectsoftypeButton.Buttondefinesthesetwoconstructors:

Button();

Button(Stringstr);

Example:Usingbuttoncontrol

//ButtonDemo.java

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=“ButtonDemo”width=250height=150>

Page 55: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</applet>

*/

publicclassButtonDemoextendsApplet

{

Stringmsg=””;

Buttonyes,no,maybe;

publicvoidinit()

{

yes=newButton(“Yes”);

no=newButton(“No”);

maybe=newButton(“Undecided”);

add(yes);add(no);add(maybe);

}

publicvoidpaint(Graphicsg)

{

g.drawString(msg,6,100);

}

}

Output:

CheckBoxesAcheckboxisacontrolthatisusedtoturnanoptiononoroff.Checkboxescanbe

Page 56: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

used individuallyoraspartofagroup.Checkboxesareobjectsof theCheckboxclass.Checkboxsupportstheseconstructors:

Checkbox();

Checkbox(Stringstr);

Checkbox(Stringstr,booleanon)

Checkbox(Stringstr,booleanon,CheckboxGroupcbGroup);

Checkbox(Stringstr,CheckboxGroupcbGroup,booleanon)

Thefirstformcreatesacheckboxwhoselabelisinitiallyblank.Thestateofthecheckboxisunchecked.

Thesecondformcreatesacheckboxwhoselabelisspecifiedbystr.Thestateofthecheckboxisunchecked.

Thethirdformallowsustosettheinitialstateofthecheckbox.Ifonistrue,thecheckboxisinitiallychecked;otherwise,itiscleared.

The fourth and fifth forms create a check box whose label is specified by str andwhose group is specified by cbGroup. If this check box is not part of a group, thencbGroupmustbenull.Thevalueofondeterminestheinitialstateofthecheckbox.

In order to retrieve the current state of a check box, call getState( ). For setting itsstate, call setState( ).We can obtain the current label associated with a check box bycallinggetLabel().Forsettingthelabel,setLabel()isused.Thesemethodsareasfollows:

booleangetState();

voidsetState(booleanon);

StringgetLabel();

voidsetLabel(Stringstr);

Example:Demonstratecheckboxes.

//CheckboxDemo.java

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=“CheckboxDemo”width=250height=200>

</applet>

*/

publicclassCheckboxDemoextendsApplet

{

Stringmsg=””;

Page 57: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

CheckboxWin98,winNT,solaris,mac;

publicvoidinit()

{

Win98=newCheckbox(“Windows98/XP”,null,true);

winNT=newCheckbox(“WindowsNT/2000”);

solaris=newCheckbox(“Solaris”);

mac=newCheckbox(“MacOS”);

add(Win98);

add(winNT);

add(solaris);

add(mac);

}

publicvoidpaint(Graphicsg)

{

}

}

Output:

CheckboxGroup/OptionButtonOnlyonecheckboxinthegroupcanbecheckedatanyonetime.Thesecheckboxes

areoftencalled radiobuttons.Forcreatinga setofmutuallyexclusivecheckboxes,wemustfirstdefinethegrouptowhichtheywillbelongandthenspecifythatgroupwhenweconstructthecheckboxes. Check box groups are objects of typeCheckboxGroup.Onlythedefaultconstructorisdefined,whichcreatesanemptygroup.

Page 58: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

We can determine which check box in a group is currently selected by callinggetSelectedCheckbox().WecansetacheckboxbycallingsetSelectedCheckbox().Thesemethodsareasfollows:

CheckboxgetSelectedCheckbox()

voidsetSelectedCheckbox(Checkboxwh)

Example:Hereisaprogramthatusescheckboxesthatarepartofagroup.

//CBGroup.java

importjava.awt.*;importjava.applet.*;

/*

<appletcode=“CBGroup”width=250height=200>

</applet>

*/

publicclassCBGroupextendsApplet

{

Stringmsg=””;

CheckboxWin98,winNT,solaris,mac;

CheckboxGroupcbg;

publicvoidinit()

{

cbg=newCheckboxGroup();

Win98=newCheckbox(“Windows98/XP”,cbg,true);

winNT=newCheckbox(“WindowsNT/2000”,cbg,false);

solaris=newCheckbox(“Solaris”,cbg,false);

mac=newCheckbox(“MacOS”,cbg,false);

add(Win98);

add(winNT);add(solaris);add(mac);

}

publicvoidpaint(Graphicsg)

{

msg=“Currentselection:“;

msg+=cbg.getSelectedCheckbox().getLabel();

g.drawString(msg,6,100);

Page 59: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

}

}

Output:

ChoiceControlsTheChoice class is used to create a pop-up list of items fromwhich the usermay

choose.Choiceonlydefinesthedefaultconstructor,whichcreatesanemptylist.Inordertoaddaselectiontothelist,add()isused.Ithasthisgeneralform:

voidadd(Stringname)

Here,nameisthenameoftheitembeingadded.Inordertodeterminewhichitemiscurrentlyselected,wemaycalleitheranyofthefollowingmethods:

StringgetSelectedItem();

intgetSelectedIndex();

The getSelectedItem( ) method returns a string containing the name of the item.getSelectedIndex()returnstheindexoftheitem.Thefirstitemisatindex0.Bydefault,thefirstitemaddedtothelistisselected.Forobtainingthenumberofitemsinthelist,callgetItemCount( ).Wecan set the currently selected itemusing the select( )methodwitheither a zero-based integer index or a string that will match a name in the list. Thesemethodsareshownhere:

intgetItemCount();

voidselect(intindex);

voidselect(Stringname);

Given an index, we can obtain the name associated with the item at that index bycallinggetItem(),whichhasthisgeneralform:

Page 60: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

StringgetItem(intindex);

Example:DemonstrateChoicelists.

//ChoiceDemo.java

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=“ChoiceDemo”width=300height=180>

</applet>

*/

publicclassChoiceDemoextendsApplet

{

Choiceos,browser;Stringmsg=””;

publicvoidinit()

{

os=newChoice();

browser=newChoice();

os.add(“Windows 98/XP”); os.add(“Windows NT/2000”); os.add(“Solaris”);os.add(“MacOS”); browser.add(“Netscape 3.x”); browser.add(“Netscape 4.x”);browser.add(“Netscape5.x”);browser.add(“Netscape6.x”);

browser.add(“Internet Explorer 4.0”); browser.add(“Internet Explorer 5.0”);browser.add(“Internet Explorer 6.0”); browser.add(“Lynx 2.4”);browser.select(“Netscape4.x”);

add(os);

add(browser);

}

publicvoidpaint(Graphicsg)

{

}

}

Output:

Page 61: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

ListsTheList classprovides a compact,multiple-choice, scrolling selection list.TheList

object canbeconstructed to showanynumberof choices in thevisibleWindow. It canalsobecreatedtoallowmultipleselections.Listprovidestheseconstructors:

List();

List(intnumRows);

List(intnumRows,booleanmultipleSelect);

ThefirstversioncreatesaListcontrolthatallowsonlyoneitemtobeselectedatanyonetime.Inthesecondform,thevalueofnumRowsspecifiesthenumberofentriesinthelist thatwillalwaysbevisible (otherscanbescrolled intoviewasneeded). In the thirdform,ifmultipleSelectistrue,thentheusermayselecttwoormoreitemsatatime.Ifitisfalse, thenonlyoneitemmaybeselected.Foraddingaselectiontothelist,wecancalladd().Ithasthefollowingtwoforms:

voidadd(Stringname);

voidadd(Stringname,intindex);

Here,nameisthenameoftheitemaddedtothelist.Thefirstformaddsitemstotheendofthelist.Thesecondformaddstheitemattheindexspecifiedbyindex.

For lists that allow multiple selection, we must use either getSelectedItems( ) orgetSelectedIndexes(),shownhere,todeterminethecurrentselections:

String[]getSelectedItems();

int[]getSelectedIndexes();

ThegetSelectedItems()returnsanarraycontainingthenamesofthecurrentlyselecteditems. getSelectedIndexes( ) returns an array containing the indexes of the currentlyselecteditems.Inordertoobtainthenumberofitemsinthelist,callgetItemCount().Wecansetthecurrentlyselecteditembyusingtheselect()methodwithazero-basedintegerindex.Thesemethodsareshownhere:

intgetItemCount();

voidselect(intindex);

Page 62: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Given an index, we can obtain the name associated with the item at that index bycallinggetItem(),whichhasthisgeneralform:

StringgetItem(intindex)

Here,indexspecifiestheindexofthedesireditem.

Example:ListDemonstration

//ListDemo.java

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=“ListDemo”width=300height=180>

</applet>

*/

publicclassListDemoextendsApplet

{

Listos,browser;Stringmsg=””;publicvoidinit()

{

os = new List(4, true); browser = new List(4, false); os.add(“Windows 98/XP”);os.add(“Windows NT/2000”); os.add(“Solaris”); os.add(“MacOS”);browser.add(“Netscape 3.x”); browser.add(“Netscape 4.x”); browser.add(“Netscape5.x”);browser.add(“Netscape6.x”);

browser.add(“InternetExplorer4.0”);

browser.add(“Internet Explorer 5.0”); browser.add(“Internet Explorer 6.0”);browser.add(“Lynx2.4”);browser.select(1);

add(os);

add(browser);

}

publicvoidpaint(Graphicsg)

{

intidx[];

msg=“CurrentOS:“;

idx=os.getSelectedIndexes();

for(inti=0;i<idx.length;i++)

msg+=os.getItem(idx[i])+”“;

Page 63: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

g.drawString(msg,6,120);

msg=“CurrentBrowser:“;

msg+=browser.getSelectedItem();

g.drawString(msg,6,140);

}

}

Output:

TextField

TextComponent

TextArea

TextField

Page 64: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Fig.Textcomponentshierarchy

The TextField class implements a single-line text-entry area, usually called an editcontrol.Textfieldsallowtheusertoenterstringsandtoeditthetextusingthearrowkeys,cut and paste keys, and mouse selections. TextField is a subclass of TextComponent.TextFielddefinesthefollowingconstructors:

TextField();

TextField(intnumChars);

TextField(Stringstr);

TextField(Stringstr,intnumChars);

Thefirstversioncreatesadefaulttextfield.ThesecondformcreatesatextfieldthatisnumChars characters wide. The third form initializes the text field with the stringcontainedinstr.Thefourthforminitializesatextfieldandsetsitswidth.TextField(andits superclass TextComponent) provides several methods that allow us to utilize a textfield.Inordertoobtainthestringcurrentlycontainedinthetextfield,wecanusegetText().Forsettingthetext,wecallsetText().Thesemethodsareasfollows:

StringgetText();

voidsetText(Stringstr);

Here,stristhenewstring.Theusercanselectaportionofthetextinatextfield.Also,wecanselectaportionoftextunderprogramcontrolbyusingselect().Ourprogramcanobtain the currently selected text by calling the getSelectedText( ). These methods areshownhere:

StringgetSelectedText();

voidselect(intstartIndex,intendIndex);

The getSelectedText( ) returns the selected text. The select( ) method selects thecharactersbeginningatstartIndexandendingatendIndex–1.Wecancontrolwhetherthecontents of a text fieldmay bemodified by the user by calling setEditable( ).We candetermineeditabilitybycallingisEditable().Thesemethodsareshownhere:

booleanisEditable()

voidsetEditable(booleancanEdit)

The isEditable( ) returns true if the text may be changed and false if not. InsetEditable(),ifcanEditistrue,thetextmaybechanged.Ifitisfalse,thetextcannotbealtered.Theremaybetimeswhenwewillwanttheusertoentertextthatisnotdisplayed,suchas apassword.Youcandisable theechoingof thecharacters as theyare typedbycallingsetEchoChar().Thismethod specifies a single character that theTextFieldwilldisplaywhencharactersareentered(thus,theactualcharacterstypedwillnotbeshown).WecancheckatextfieldtoseeifitisinthismodewiththeechoCharIsSet()method.We

Page 65: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

canretrievetheechocharacterbycallingthegetEchoChar()method.Thesemethodsareasfollows:

voidsetEchoChar(charch);

booleanechoCharIsSet();

chargetEchoChar();

Here,chspecifiesthecharactertobeechoed.

Example:UsingTextField

//TextFieldDemo.java

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=“TextFieldDemo”width=380height=150>

</applet>

*/

publicclassTextFieldDemoextendsApplet

{

TextFieldname,pass;

publicvoidinit()

{

Label namep = new Label(“Name: “, Label.RIGHT); Label passp = newLabel(“Password:“,Label.RIGHT);name=newTextField(12);

pass=newTextField(8);pass.setEchoChar(‘?’);add(namep);

add(name);

add(passp);

add(pass);

}

publicvoidpaint(Graphicsg)

{

}

}

Output:

Page 66: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

TextAreaSometimesasinglelineoftextinputisnotenoughforagiventask.Tohandlethese

situations,theAWTincludesasimplemultilineeditorcalledTextArea.FollowingaretheconstructorsforTextArea:

TextArea();

TextArea(intnumLines,intnumChars);

TextArea(Stringstr);

TextArea(Stringstr,intnumLines,intnumChars);

TextArea(Stringstr,intnumLines,intnumChars,intsBars);

Here,numLinesspecifiestheheight,inlines,ofthetextarea,andnumCharsspecifiesitswidth,incharacters.Initialtextcanbespecifiedbystr.Inthefifthformwecanspecifythescrollbarsthatwewantthecontroltohave.sBarsmustbeoneofthesevalues:

SCROLLBARS_BOTH

SCROLLBARS_NONE

SCROLLBARS_HORIZONTAL_ONLY

SCROLLBARS_VERTICAL_ONLY

TextArea is a subclass of TextComponent. Therefore, it supports the getText( ),setText(), getSelectedText(), select(), isEditable( ), and setEditable( ) methodsdescribedintheprecedingsection.TextAreaaddsthefollowingmethods:

voidappend(Stringstr);

voidinsert(Stringstr,intindex);

voidreplaceRange(Stringstr,intstartIndex,intendIndex);

Theappend()methodappendsthestringspecifiedbystrtotheendofthecurrenttext.Theinsert()insertsthestringpassedinstratthespecifiedindex.Inordertoreplacetext,wecallreplaceRange().ItreplacesthecharactersfromstartIndextoendIndex–1,withthereplacementtextpassedinstr.Textareasarealmostself-containedcontrols.

Page 67: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Example:UsingTextAreaControl

//TextAreaDemo.java

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=“TextAreaDemo”width=300height=250>

</applet>

*/

publicclassTextAreaDemoextendsApplet

{

publicvoidinit()

{

Stringval=“Therearetwowaysofconstructing”+“asoftwaredesign.\n”+

“Onewayistomakeitsosimple\n”+

“thatthereareobviouslynodeficiencies.\n”+

“And the otherway is tomake it so complicated\n” + “that there are no obviousdeficiencies.\n\n”+

”-C.A.R.Hoare\n\n”+

“There’sanoldstoryaboutthepersonwhowished\n”+

“his computer were as easy to use as his telephone.\n” + “That wish has cometrue,\n”+

“since I no longer know how to use my telephone.\n\n” + ” -Bjarne Stroustrup,AT&T,(inventorofC++)”;

TextAreatext=newTextArea(val,10,30);

add(text);

}

}

Output:

Page 68: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

LayoutManagersAllofthecomponentsthatwehaveshownsofarhavebeenpositionedbythedefault

layoutmanager.A layoutmanagerautomaticallyarrangesourcontrolswithinawindowbyusingsometypeofalgorithm.

EachContainerobjecthasalayoutmanagerassociatedwithit.AlayoutmanagerisaninstanceofanyclassthatimplementstheLayoutManagerinterface.ThelayoutmanagerissetbythesetLayout()method.IfnocalltosetLayout()ismade,thenthedefaultlayoutmanagerisused.Wheneveracontainerisresized(orsizedforthefirst time), thelayoutmanagerisusedtopositioneachofthecomponentswithinit.

Fig.LayoutManagersatwork

ThesetLayout()methodhasthefollowinggeneralform:

voidsetLayout(LayoutManagerlayoutObj);

Here,layoutObjisareferencetothedesiredlayoutmanager.Ifwewishtodisablethelayoutmanagerandpositioncomponentsmanually,passnullforlayoutObj.Ifwedothis,wewillneedtodeterminetheshapeandpositionofeachcomponentmanually,usingthesetBounds()methoddefinedbyComponent.

Each layout manager keeps track of a list of components that are stored by theirnames. The layout manager is notified each time we add a component to a container.

Page 69: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Wheneverthecontainerneedstoberesized,thelayoutmanagerisconsultedviaitsminimumLayoutSize()andpreferredLayoutSize()methods.EachcomponentthatisbeingmanagedbyalayoutmanagercontainsthegetPreferredSize()andgetMinimumSize()methods.These return the preferred and minimum size required todisplayeachcomponent. Javahas severalpredefinedLayoutManagerclasses, severalofwhicharedescribednext.Wecanusethelayoutmanagerthatbestfitsourapplication.

FlowLayoutFlowLayoutisthedefaultlayoutmanager.Componentsarelaidoutfromtheupper-left

corner, left torightandtoptobottom.Whennomorecomponentsfitonaline,thenextoneappearson thenext line.Asmall space is leftbetweeneachcomponent, aboveandbelow,aswellasleftandright.HerearetheconstructorsforFlowLayout:

FlowLayout();

FlowLayout(inthow);

FlowLayout(inthow,inthorz,intvert);

The first form creates the default layout,which centers components and leaves fivepixelsofspacebetweeneachcomponent.Thesecondformletsusspecifyhoweachlineisaligned.Validvaluesforhowareasfollows:

FlowLayout.LEFT

FlowLayout.CENTER

FlowLayout.RIGHT

Thesevaluesspecifyleft,center,andrightalignment,respectively.Thethirdformallowsustospecifythehorizontalandverticalspaceleftbetweencomponentsinhorzandvert,respectively.HereisaversionoftheCheckboxDemoappletshownearlier,modifiedsothatitusesleft-alignedflowlayout.

//FlowLayoutDemo.java

importjava.awt.*;

importjava.applet.*;

/*

<appletcode=“FlowLayoutDemo”width=400height=200>

</applet>

*/

publicclassFlowLayoutDemoextendsApplet

{

Stringmsg=””;

CheckboxWin98,winNT,solaris,mac;

Page 70: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

publicvoidinit()

{

Win98=newCheckbox(“Windows98/XP”,null,true);

winNT=newCheckbox(“WindowsNT/2000”);

solaris=newCheckbox(“Solaris”);

mac=newCheckbox(“MacOS”);

setLayout(newFlowLayout(FlowLayout.CENTER));

add(Win98);add(winNT);add(solaris);add(mac);

}

publicvoidpaint(Graphicsg)

{

}

}

Output:

BorderLayoutTheBorderLayoutclassimplementsacommonlayoutstylefortop-levelwindows.It

hasfournarrow,fixed-widthcomponentsattheedgesandonelargeareainthecenter.Thefoursidesarereferredtoasnorth,south,east,andwest.Themiddleareaiscalledthecenter.HerearetheconstructorsdefinedbyBorderLayout:

BorderLayout();

BorderLayout(inthorz,intvert);

Thefirstformcreatesadefaultborderlayout.Thesecondallowsustospecifythehorizontalandverticalspaceleftbetweencomponentsinhorzandvert,respectively.BorderLayoutdefinesthefollowingconstantsthatspecifytheregions:

BorderLayout.CENTER

Page 71: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

BorderLayout.SOUTH

BorderLayout.EAST

BorderLayout.WEST

BorderLayout.NORTH

Whenaddingcomponents,wewillusetheseconstantswiththefollowingformofadd(),whichisdefinedbyContainer:

voidadd(ComponentcompObj,Objectregion);

Here,compObjisthecomponenttobeadded,andregionspecifieswherethecomponentwillbeadded.HereisanexampleofaBorderLayoutwithacomponentineachlayoutarea:

//BorderLayoutDemo.java

importjava.awt.*;importjava.applet.*;

/*

<appletcode=“BorderLayoutDemo”width=400height=200>

</applet>

*/

publicclassBorderLayoutDemoextendsApplet

{

publicvoidinit()

{

setLayout(newBorderLayout());

add(newButton(“Thisisacrossthetop.”),BorderLayout.NORTH);

add(newLabel(“Thefootermessagemightgohere.”),BorderLayout.SOUTH);

add(newButton(“Right”),BorderLayout.EAST);

add(newButton(“Left”),BorderLayout.WEST);

Stringmsg=“Thereasonablemanadapts”+

“himselftotheworld;\n”+

“the unreasonable one persists in ” + “trying to adapt the world to himself.\n” +“Thereforeallprogressdepends”+

“ontheunreasonableman.\n\n”+

”-GeorgeBernardShaw\n\n”;

add(newTextArea(msg),

Page 72: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

BorderLayout.CENTER);

}

}

Output:

PRACTICAL 7:WRITEAPROGRAMTHATHASONLYONEBUTTONINTHEFRAME,CLICKINGONTHEBUTTONCYCLESTHROUGHTHECOLORS:RED->GREEN->BLUE->ANDSOON.ONECOLORCHANGEPERCLICK. (USE GETBACKGROUND() METHOD TO GET THE CURRENTCOLOR)SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAWTPrograminJAVAusingButtonControl

LearnHowtohandleButtonEventsusingActionListenerinterfaces.

LEARNINGOUTCOMESExplain&PracticeButtonEvents.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE

importjava.awt.*;

Page 73: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

importjava.applet.*;

importjava.awt.event.*;

importjava.lang.String;

classChangeColorextendsAppletimplementsActionListener{

Buttonb1;

publicvoidinit()

{

b1=newButton(“ChangeColor”);

add(b1);

b1.addActionListener(this);

}

publicvoidactionPerformed(ActionEvente)

{

if(e.getSource()==b1)

{

Strings;

s=b1.getBackground();

if(s==“ChangeColor”)

{

this.setBackground(Color.RED);

b1.setLabel(“Green”);

}

if(s==“Green”)

{

this.setBackground(Color.GREEN);

b1.setLabel(“Blue”);

}

if(s==“Blue”)

{

this.setBackground(Color.BLUE);

b1.setLabel(“ChangeColor”);

Page 74: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

}

}

}

}

publicclassColorPickerDemoextendsFrame

{

publicstaticvoidmain(String[]args)

{

Framef=newFrame(“ColorPickerDemo”);

ChangeColorc=newChangeColor();

c.init();

f.add(“Center”,c);

f.pack();

f.show();

}

}

OUTPUT:

PRACTICAL8:WRITEANAPPLETTHATCONTAINSTHREECHECKBOXESAND30X30PIXELCANVAS.THETHREECHECKBOXESSHOULDBELABELED“RED”,”GREEN”,”BLUE”.THESELECTIONOFTHECHECKBOXESDETERMINESTHECOLOROFTHECANVAS.FOREXAMPLE,IFTHEUSERSELECTSBOTH“RED”AND“BLUE”,THECANVASSHOULDBEPURPLE.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAWTPrograminJAVAusingCheckboxandCanvasControl

Page 75: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

LearnHowtohandleCheckboxEventsusingItemListenerinterfaces.

LEARNINGOUTCOMESExplain&PracticeCheckboxEvents.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE:

importjava.awt.*;

importjava.applet.*;

importjava.awt.event.*;

importjava.lang.String;

publicclassCanvasColorDemoextendsAppletimplementsItemListener

{

Checkboxch1,ch2,ch3;

intc1,c2,c3;

//c1=c2=c3=0;

Canvasc=newCanvas();

publicvoidinit()

{

setLayout(newGridLayout(1,4));

//ColorGroup=newCheckboxGroup();

ch1=newCheckbox(“RED”,false);

ch2=newCheckbox(“GREEN”,false);

ch3=newCheckbox(“BLUE”,false);

add(ch1);

add(ch2);

add(ch3);

ch1.addItemListener(this);

Page 76: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

ch2.addItemListener(this);

ch3.addItemListener(this);

c.setBackground(Color.CYAN);

c.setVisible(true);

add(c);

}

publicvoiditemStateChanged(ItemEvente)

{

if(e.getSource()==ch1)

if(c1!=255)

c1=255;

else

c1=0;

if(e.getSource()==ch2)

if(c2!=255)

c2=255;

else

c2=0;

if(e.getSource()==ch3)

if(c3!=255)

c3=255;

else

c3=0;

c.setBackground(newColor(c1,c2,c3));

repaint();

}

}

OUTPUT:

Page 77: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

PRACTICAL9:CREATEANAPPLICATIONTHATDISPLAYSAFRAME

WITHAMENUBAR.WHENAUSERSELECTSANYMENUORMENUITEM,DISPLAYTHATSELECTIONONATEXTAREAINTHECENTEROFTHEFRAME

SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAWTPrograminJAVAusingMenuandTextArea

LearnHowtohandleMenuEventsusingActionListenerinterfaces.

LEARNINGOUTCOMESExplain&PracticeMenuEvents.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE:

/*MenuDemo.java*/

importjava.awt.*;

importjava.awt.event.*;

importjava.applet.*;

publicclassMenuDemoextendsAppletimplementsActionListener

{

privateTextFieldmyTextField;

privateFramemyFrame;

Page 78: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

publicvoidinit()

{

myFrame=newFrame();

myFrame.addWindowListener(newTerminator());

myTextField=newTextField(20);

add(myTextField);

myFrame.setBounds(200,200,300,300);

//placemyMenuBarattopofmyFrame

MenuBarmyMenuBar=newMenuBar();

myFrame.setMenuBar(myMenuBar);

MenufileMenu=newMenu(“File”);

myMenuBar.add(fileMenu);

MenueditMenu=newMenu(“Edit”);

myMenuBar.add(editMenu);

MenuItemmyMenuItem;

myMenuItem=newMenuItem(“Open”);

myMenuItem.addActionListener(this);

fileMenu.add(myMenuItem);

myMenuItem=newMenuItem(“Close”);

myMenuItem.addActionListener(this);

fileMenu.add(myMenuItem);

myMenuItem=newMenuItem(“Undo”);

myMenuItem.addActionListener(this);

editMenu.add(myMenuItem);

Page 79: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

myFrame.show();

}

publicvoidactionPerformed(ActionEvente)

{

if(e.getSource()instanceofMenuItem)

myTextField.setText(“YourChoice:”

+e.getActionCommand());

}

publicclassTerminator

extendsWindowAdapter

{

publicvoidwindowClosing(WindowEvente)

{

myFrame.dispose();

//useSystem.exit(0)forapplications

}

}

}

OUTPUT:

PRACTICAL10:WRITEANAPPLETTHATDRAWSTWOSETSOFEVER-DECREASINGRECTANGLESONEINOUTLINEFORMANDONEFILLEDALTERNATELYINBLACKANDWHITE.

Page 80: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopanAWTPrograminJAVAusingGraphicsClassMethodslikedrawRect()andfillRect()

LEARNINGOUTCOMESExplain&PracticeGraphicsClassMethods.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

CODE:

importjava.awt.*;

importjava.awt.event.*;

importjava.applet.*;

publicclassRectAppletextendsApplet

{

publicstaticfinalintW=200;

publicstaticfinalintH=200;

publicvoidpaint(Graphicsg)

{

g.setColor(Color.BLACK);

g.fillRect(0,0,getWidth(),getHeight());

g.setColor(Color.WHITE);

for(intx=0;x<getWidth()/2;x+=5)

{

intx1=(getWidth()/2)-x;

inty1=(getHeight()/2)-x;

Page 81: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

g.drawRect(x1,y1,x*2,x*2);

}

}

publicstaticvoidmain(Stringargs[])

{

Appletapplet=newRectApplet();

Frameframe=newFrame();

frame.addWindowListener(newWindowAdapter()

{

publicvoidwindowClosing(WindowEvente)

{

System.exit(0);

}

});

frame.add(applet);

frame.setSize(W,H);

frame.show();

}

}

OUTPUT:

EXERCISE:

Page 82: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

DEVELOPANAPPLETTODISPLAYTHEMESSAGE“HAPPYNEWYEAR”WITHINATEXTFIELD.

Code:

Page 83: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

EXTENDTHEPREVIOUSPROGRAMSOTHATTHEMESSAGE“HAPPYNEWYEAR”WILLAPPEARWITHINATEXTFIELDWHENTHEBUTTONWITHTHECAPTION“YEAR”ISPUSHED,WHILETHEMESSAGE“HAPPYNEWMILLENIUM”WILLAPPEARWITHINTHETEXTFIELDWHENTHEBUTTONWITHTHECAPTION“MILLENIUM”ISPUSHED.

Code:

Page 84: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

BUILDANAPPLETTHATRECEIVESTHERADIUSOFACIRCLETHROUGHATEXTFIELDANDCOMPUTESTHEAREAWHENTHEBUTTON“AREA”ISPUSHED.THEAREASHOULDAPPEARINASEPERATETEXTFIELD.THEFIRSTTEXTFIELDSHOULDBEPRECEEDEDBYTHELABEL“ENTER

Page 85: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

THERADIUS”,WHILETHESECONDTEXTFIELDSHOULDBEPRECEEDEDBYTHELABEL“AREA

ISEQUALTO”.

Code:

Page 86: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

CREATETWOCHECKBOXESWITHTHECAPTION“COM”AND“COBRA”.CREATETWOTEXTFIELDS.USETHEFIRSTTOINDICATETHESTATUSOFTHEFIRSTCHECKBOXANDTHESECONDTEXTFIELDTOINDICATETHESTATUSOFTHESECONDCHECKBOX.

Code:

Page 87: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

Page 88: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

WRITEANAPPLETTODISPLAYFOURRADIOBUTTONSWITHTHECAPTIONS“SANDWICH1”,“SANDWICH2”,“SANDWICH3”AND“SANDWICH4”.CREATEATEXTFIELDANDUSEITTOINDICATEWHICHDISHISSELECTED.

Code:

Page 89: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

CREATEACHOICECONTROLTOSELECTONEOFTHEFOURFONTS“TIMES”,“SARIF”,“SANSARIF”AND“ROMAN”.CREATEANOTHERCHOICECONTROLTOSELECTONOFTHEFIVECOLOURSGREEN,RED,YELLOW,WHITEANDORANGE.MAKEPROVISIONTOREPORTTHESELECTEDCOLOURINTHEFORMOFALABEL.

Code:

Page 90: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

AMENUBARCONTAINS3MENUSNAMEDSALESFILE1,SALESFILE2,ANDSALESFILE3.EACH

ONEOFTHESE3MENUSHASTHE3OPTIONSNAMEDCREATE,UPDATEANDPRINT.WRITEANAPPLETFORCREATINGANDDISPLAYINGALLTHE3MENUSWITHTHEIROPTIONS.

Code:

Page 91: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29
Page 92: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

Page 93: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

UNIT3

GENERALOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnhowtouseJDBCtoconnectdatabase.

DevelopandexecuteaJDBCapplicationtocreate/read/update/deleterecordsintodatabase.

LearnhowtouseJDBCAPIandJDBCDriversfordatabaefunctions.

LEARNINGOUTCOMESExplainJDBCconceptsandPracticeJDBCprograms.

ASSUMPTIONSOracleJDKinstalled,MySQLJavaConnectorinstalledandconfigured.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

INTRODUCTIONJDBCstandsforJavaDatabaseConnectivity,whichisastandardJavaAPIfor

database-independentconnectivitybetweentheJavaprogramminglanguageandawiderangeofdatabases.

TheJDBClibraryincludesAPIsforeachofthetaskscommonlyassociatedwithdatabaseusage:

MakingaconnectiontoadatabaseCreatingSQLorMySQLstatementsExecutingthatSQLorMySQLqueriesinthedatabaseViewing&Modifyingtheresultingrecords

Thebasicstepstogetyourprogramupandrunningare:

LoadthedriverandregisteritwiththedrivermanagerConnecttoadatabaseCreateastatementExecuteaqueryandretrievetheresults,ormakechangestothedatabaseDisconnectfromthedatabase

Steps1and2aretheonlyDBMS-specificsteps.

HereisthecodethatloadsthedriverandregistersitwiththeJDBCdrivermanager:

DriverManager.registerDriver(newcom.mysql.jdbc.Driver());

Hereisanotherwayofdoingtheabove:

Page 94: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Class.forName(“com.mysql.jdbc.Driver”);

Followingaredriverstringforsomeofthepopulardatabases,

MySQLJDBCConnectionURL:jdbc:mysql://hostname:3306/–3306ismysqldefaultport

JavaDBConnectionURL:jdbc:derby:testdb;create=true

MicrosoftSQLServerJDBCConnectionURL:jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=northwind

OracleJDBCconnectionURL:jdbc:oracle:thin:@hostname:1521:MyDatabase

ConnectingtoaDatabaseTheDriverManagerclassprovidesthestaticgetConnection()methodforopeninga

databaseconnection.BelowisthemethoddescriptionforgetConnection():public static Connection getConnection(String url, String userid, String password)

throwsSQLException

GettingconnectionConnectionconnection=DriverManager.getConnection(“jdbc:jdbcDriver:database”,

username,password);

QueryexecutionandgettingresultStatementstatement=connection.createStatement();

ResultSetresultSet=statement.executeQuery(“SELECT*FROMtable”);

ParsingtheresultfromResultSetwhile(resultSet.next()){

intfield1=rs.getInt(“field1”);

Stringfield2=rs.getString(“field2”);

}

PRACTICAL 11: WRITE A DATABASE APPLICATION THAT USES ANYJDBCDRIVER.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnhowtouseJDBCtoconnecttodatabase.

Page 95: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

LearnhowtouseJDBCAPIandJDBCDriversfordatabaefunctions.

LEARNINGOUTCOMESExplainJDBCconceptsandPracticeJDBCprogramstoconnecttoMySQLDatabase.

ASSUMPTIONSOracleJDKinstalled,MySQLJavaConnectorinstalledandconfigured.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,path,classpathareconfigured.

CODE

//STEP1.Importrequiredpackages

importjava.sql.*;

publicclassJDBCExample{

//JDBCdrivernameanddatabaseURL

staticfinalStringJDBC_DRIVER=“com.mysql.jdbc.Driver”;

staticfinalStringDB_URL=“jdbc:mysql://localhost/”;

//Databasecredentials

staticfinalStringUSER=“root”;

staticfinalStringPASS=””;

publicstaticvoidmain(String[]args){

Connectionconn=null;

Statementstmt=null;

try{

//STEP2:RegisterJDBCdriver

Class.forName(“com.mysql.jdbc.Driver”);

//STEP3:Openaconnection

System.out.println(“Connectingtodatabase…”);

conn=DriverManager.getConnection(DB_URL,“USER”,“PASS”);

//STEP4:Executeaquery

System.out.println(“Creatingdatabase…”);

Page 96: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

stmt=conn.createStatement();

Stringsql=“CREATEDATABASESTUDENTS”;

stmt.executeUpdate(sql);

System.out.println(“Databasecreatedsuccessfully…”);

}catch(SQLExceptionse){

//HandleerrorsforJDBC

se.printStackTrace();

}catch(Exceptione){

//HandleerrorsforClass.forName

e.printStackTrace();

}finally{

//finallyblockusedtocloseresources

try{

if(stmt!=null)

stmt.close();

}catch(SQLExceptionse2){

}//nothingwecando

try{

if(conn!=null)

conn.close();

}catch(SQLExceptionse){

se.printStackTrace();

}//endfinallytry

}//endtry

System.out.println(“Goodbye!”);

}//endmain

}//endJDBCExample

OUTPUT:

Connectingtodatabase…

Creatingdatabase…

Page 97: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Databasecreatedsuccessfully…

Goodbye!

Processcompleted.

PRACTICAL12:DEVELOPAUITHATPERFORMSTHEFOLLOWINGSQLOPERATIONS:1)INSERT2)DELETE3)UPDATE.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnhowtouseJDBCtoperformCRUDOperation(Create/Read/Update/Delete)

LearnhowtouseJDBCAPIandJDBCDriversfordatabaefunctions.

LEARNINGOUTCOMESExplainJDBCconceptsandPracticedatabaseoperationsusingJDBC.

ASSUMPTIONSOracleJDKinstalled,MySQLJavaConnectorinstalledandconfigured.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,path,classpathareconfigured.

CODE

importjava.awt.Container;

importjava.awt.GridLayout;

importjava.awt.event.ActionEvent;

importjava.awt.event.ActionListener;

importjava.sql.Connection;

importjava.sql.DriverManager;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.swing.BoxLayout;

importjavax.swing.JButton;

importjavax.swing.JFrame;

Page 98: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

importjavax.swing.JLabel;

importjavax.swing.JPanel;

importjavax.swing.JTextField;

publicclassJDBCCRUDimplementsActionListener{

JLabellblFname,lblLname,lblf,lbll;

JLabellblfVal,lbllVal;

JTextFieldtxtFname,txtLname;

JButtonbtnInsert,btnUpdate,btnDelete,btnPrev,btnNext,btnClear;

Connectioncon;

ResultSetrs;

publicstaticvoidmain(String[]args){

JDBCCRUDobj=newJDBCCRUD();

obj.createUI();

obj.connect();

}

privatevoidcreateUI()

{

JFrameframe=newJFrame(“JDBCCREATE/READ/UPDATE/DELETE”);

//LayoutofMainWindow

Containerc=frame.getContentPane();

c.setLayout(newBoxLayout(c,BoxLayout.Y_AXIS));

lblFname=newJLabel(“FirstName:”);

lblLname=newJLabel(“LastName:”);

txtFname=newJTextField(””,15);//Toadjustwidth

txtLname=newJTextField();

JPanelpnlInput=newJPanel(newGridLayout(4,2));

pnlInput.add(lblFname);

pnlInput.add(txtFname);

pnlInput.add(lblLname);

Page 99: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

pnlInput.add(txtLname);

btnInsert=newJButton(“Insert”);

btnInsert.addActionListener(this);

btnUpdate=newJButton(“Update”);

btnUpdate.addActionListener(this);

btnDelete=newJButton(“Delete”);

btnDelete.addActionListener(this);

btnClear=newJButton(“Clear”);

btnClear.addActionListener(this);

JPanelpnlButton=newJPanel(newGridLayout(1,4));

pnlButton.add(btnInsert);

pnlButton.add(btnUpdate);

pnlButton.add(btnDelete);

pnlButton.add(btnClear);

JPanelpnlAns=newJPanel(newGridLayout(4,2));

lblf=newJLabel(“FirstName:”);

lbll=newJLabel(“LastName:”);

lblfVal=newJLabel(””);

lbllVal=newJLabel(””);

pnlAns.add(lblf);

pnlAns.add(lblfVal);

pnlAns.add(lbll);

pnlAns.add(lbllVal);

btnPrev=newJButton(”<<“);

btnPrev.setActionCommand(“Prev”);

btnPrev.addActionListener(this);

btnNext=newJButton(”>>“);

btnNext.setActionCommand(“Next”);

btnNext.addActionListener(this);

JPanelpnlNavigate=newJPanel(newGridLayout(1,2));

Page 100: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

pnlNavigate.add(btnPrev);

pnlNavigate.add(btnNext);

frame.add(pnlInput);

frame.add(pnlButton);

frame.add(pnlAns);

frame.add(pnlNavigate);

frame.pack();

frame.setVisible(true);

}

@Override

publicvoidactionPerformed(ActionEventevt){

Stringcmd=evt.getActionCommand();

if(cmd.equals(“Insert”))

{

insertData();

}elseif(cmd.equals(“Update”))

{

updateData();

}elseif(cmd.equals(“Delete”))

{

deleteData();

}elseif(cmd.equals(“Prev”))

{

previous();

}elseif(cmd.equals(“Next”))

{

next();

}elseif(cmd.equals(“Clear”))

{

clearControls();

}

Page 101: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

}

privatevoidconnect()

{

try

{

Class.forName(“com.mysql.jdbc.Driver”);

con=DriverManager.getConnection(“jdbc:mysql://localhost/students”,“root”,””);

}

catch(Exceptione)

{

System.out.println(“Unabletoconnect”);

}

}

privatevoiddisconnect()

{

try

{

con.close();

}

catch(Exceptione){}

}

privatevoidinsertData()

{

try

{

String sql = “Insert Into StudentData(FName,LName) ” +“Values(’”+txtFname.getText()+”’,’”+txtLname.getText()+”’)”;

Statementstatement=con.createStatement();

statement.execute(sql);

createMessageBox(“InsertedSuccessfully”);

clearControls();

rs.close();

Page 102: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

rs=null;

}

catch(Exceptione)

{

createMessageBox(e.getMessage());

}

}

privatevoidupdateData()

{

try

{

String sql=“UpdateStudentDataSetLName=’”+txtLname.getText()+“‘WhereFName=’”+txtFname.getText()+”’”;

Statementstatement=con.createStatement();

intcount=statement.executeUpdate(sql);

createMessageBox(“UpdatedSuccessfully”);

clearControls();

rs.close();

rs=null;

}

catch(Exceptione)

{

createMessageBox(e.getMessage());

}

}

privatevoiddeleteData()

{

try

{

String sql = “delete from StudentData where FName =’”+txtFname.getText()+”’”;

Statementstatement=con.createStatement();

Page 103: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

//statement.execute(sql);

statement.executeUpdate(sql);

createMessageBox(“Recordof“+txtFname.getText()+”DeletedSuccessfully”);

clearControls();

rs.close();

rs=null;

}

catch(Exceptione)

{

createMessageBox(e.getMessage());

}

}

privatevoidprevious()

{

try

{

if(rs==null)

{

Stringsql=“SelectFName,LNamefromStudentData”;

Statement statement =con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

rs=statement.executeQuery(sql);

}

if(rs.previous()&&!rs.isBeforeFirst())

{

populateControls();

}

}

catch(Exceptione)

{

Page 104: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

e.printStackTrace();

}

}

privatevoidnext()

{

try

{

if(rs==null)

{

Stringsql=“SelectFName,LNamefromStudentData”;

Statement statement =con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

rs=statement.executeQuery(sql);

}

if(rs.next()&&!rs.isAfterLast())//AfterLastwasgivinginvalidcursorstateerror

{

populateControls();

}

}

catch(Exceptione)

{

e.printStackTrace();

}

}

privatevoidcreateMessageBox(Stringmsg)

{

JFrameframe=newJFrame(“Result”);

JLabellbl=newJLabel(msg);

frame.add(lbl);

Page 105: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

frame.setSize(200,200);

frame.setVisible(true);

}

privatevoidclearControls()

{

Stringempty=””;

txtFname.setText(empty);

txtLname.setText(empty);

lblfVal.setText(empty);

lbllVal.setText(empty);

}

privatevoidpopulateControls()

{

try{

lblfVal.setText(rs.getString(“fName”));

lbllVal.setText(rs.getString(“lName”));

txtFname.setText(lblfVal.getText());

txtLname.setText(lbllVal.getText());

}

catch(SQLExceptione)

{

e.printStackTrace();

}

}

}

OUTPUT

JDBCInsertOperation

Message when u pressInsertButton

JDBCUpdateOperation

Page 106: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

ChangeThakkartoPatel Message when u pressUpdateButton

JDBCDeleteOperation

Navigate to Sanjay DhamiRecord

Message when u pressUpdateButton

PRACTICAL13:WRITEAPROGRAMTOPRESENTASETOFCHOICEFORUSERTOSELECTAPRODUCT&DISPLAYTHEPRICEOFPRODUCT.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopaJDBCPrograminJAVAusingMySQLasbackend.

LearnHowtohandleJComboBoxControlEventsusingItemListenerinterface.

LEARNINGOUTCOMESExplain&PracticefetchingvaluesbasedonselectioninJComboBoxEvents.

ASSUMPTIONSOracleJDKinstalled

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

FollowingdatabaseandtablecreatedinMySQL

Database:ProductInfo

Table:ProductTable{ProductNameChar(50),PriceNumber}

ProductName Price

Page 107: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

CD 30

PenDrive 250

CODE

importjava.awt.Container;

importjava.awt.GridLayout;

importjava.awt.event.ItemEvent;

importjava.awt.event.ItemListener;

importjava.sql.Connection;

importjava.sql.DriverManager;

importjava.sql.ResultSet;

importjava.sql.SQLException;

importjava.sql.Statement;

importjavax.swing.BoxLayout;

importjavax.swing.JButton;

importjavax.swing.JFrame;

importjavax.swing.JLabel;

importjavax.swing.JPanel;

importjavax.swing.JTextField;

importjavax.swing.JComboBox;

publicclassJDBCPriceDemo{

JLabellblItem;

JComboBoxcmbItemList;

JLabellblSelectedItem,lblItemPrice;

Stringproduct;

intprice;

Connectioncon;

ResultSetrs1;

ResultSetrs2;

publicstaticvoidmain(String[]args){

JDBCPriceDemoobj=newJDBCPriceDemo();

Page 108: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

obj.connect();

obj.createUI();}

privatevoidcreateUI()

{

JFrameframe=newJFrame(“JDBCProductPriceDemo”);

frame.setLayout(newGridLayout(3,3));

lblItem=newJLabel(“SelectProducttocheckprice:”);

JComboBoxcmbItemList=newJComboBox();

try{

Statementstmt=con.createStatement();

Stringquery=“SELECT*FROMProductTable”;

rs1=stmt.executeQuery(query);

while(rs1.next())

{

cmbItemList.addItem(rs1.getString(“ProductName”));

}

stmt.close();

rs1.close();

}

catch(Exceptione){}

lblSelectedItem=newJLabel(“Item:”);

lblItemPrice=newJLabel(“Price:”);

frame.add(lblItem);

frame.add(cmbItemList);

frame.add(lblSelectedItem);

frame.add(lblItemPrice);

ItemListeneritemListener=newItemListener(){

publicvoiditemStateChanged(ItemEventitemEvent){

product=itemEvent.getItem().toString();

try{

Statementst=con.createStatement();

Page 109: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

rs2=st.executeQuery(“SELECTPriceFROMProductTableWHEREProductName=’”+product+”’”);

if(rs2!=null)

{

rs2.next();

lblSelectedItem.setText(product.toString());

lblItemPrice.setText(String.valueOf(rs2.getInt(1)));

rs2.close();

}

}

catch(SQLExceptionex){}

catch(Exceptione){}

}

};

cmbItemList.addItemListener(itemListener);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.pack();

frame.setVisible(true);

}

privatevoidconnect()

{

try

{

Class.forName(“com.mysql.jdbc.Driver”);

con = DriverManager.getConnection(“jdbc:mysql://localhost/ProductInfo”,“root”,””);

}

catch(Exceptione)

{

System.out.println(“Unabletoconnect”);

}

Page 110: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

}

privatevoiddisconnect()

{

try

{

con.close();

}

catch(Exceptione){}

}

}

OUTPUT

EXERCISE:WRITEAJDBCPROGRAMTOIMPLEMENTTHELOGIN_IDFORMUSINGJDBC.

Code:

Page 111: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

WRITEAJDBCPROGRAMTOSELECTTHEVALUESFROMTHEDEPARTMENTTABLE.

Code:

Page 112: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

WRITEAJDBCPROGRAMTOINSERTTHEVALUESINTOTHESTUDENTTABLE.

Page 113: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Code:

Page 114: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

WRITEAJDBCPROGRAMTOALTERANDINSERTTHEVALUESINTOTABLE.

Code:

Page 115: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

WRITEAJDBCPROGRAMTODELETEARECORDBYTAKINGTHEINPUTFROMKEYBOARD.

Code:

Page 116: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Output:

Page 117: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

UNIT4

GENERALOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnhowtouseServlettodevelopwebapplications.

DevelopanddeployaServletapplicationusingApachewebserver.

LearnhowtoreadparametersinServlet.

Learnhowtoreadinitializationparametersusingweb.xmlfile.

LEARNINGOUTCOMESExplainServletconcepts

PracticeServletprograms.

ASSUMPTIONSOracleJDKinstalled,ApaheWebServerandServletAPIinstalled,configuredandrunning.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

INTRODUCTIONServlets: For development of web basd components Servlets are the Java platform

technology of choice for extending and enhancing Web servers. Servlets provide acomponent-based, platform-independent method for building Web-based applications,without the performance limitations of CGI programs. And unlike proprietary serverextensionmechanisms(suchastheNetscapeServerAPIorApachemodules),servletsareserver-andplatform-independent.Thisleavesyoufreetoselecta“bestofbreed”strategyfor your servers, platforms, and tools. Servlets have access to the entire family of JavaAPIs, includingtheJDBCAPItoaccessenterprisedatabases.Servletscanalsoaccessalibrary ofHTTP-specific calls and receive all the benefits of themature Java language,includingportability,performance,reusability,andcrashprotection.

Todayservletsareapopularchoiceforbuilding interactiveWebapplications.Third-partyservletcontainersareavailable forApacheWebServer,Microsoft IIS,andothers.ServletcontainersareusuallyacomponentofWebandapplicationservers,suchasBEAWebLogicApplicationServer,IBMWebSphere,SunJavaSystemWebServer,SunJavaSystemApplicationServer,andothers.

AsweknowthattheservletextendstheHttpServletandoverridesthedoGet()methodwhichitinheritsfromtheHttpServletclass.TheserverinvokesdoGet()methodwheneverweb server receives the GET request from the servlet. The doGet() method takes twoarguments first isHttpServletRequestobject and the secondone isHttpServletResponse

Page 118: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

objectandthismethodthrowstheServletException.

Whenever theusersendstherequest to theserver thenservergenerates twoobjects’first is HttpServletRequest object and the second one is HttpServletResponse object.HttpServletRequest object represents the client’s request and the HttpServletResponserepresentstheservlet’sresponse.

Inside thedoGet()methodour servlethas firstused thesetContentType()methodofthe response object which sets the content type of the response to text/html It is thestandard MIME content type for the html pages.After that it has used the methodgetWriter()oftheresponseobjecttoretrieveaPrintWriterobject.Todisplaytheoutputonthebrowserweusetheprintln()methodofthePrintWriterclass.

InsertingDatainDatabasetableusingStatementToaccomplishourgoalwefirsthavetomakeaclassnamedasServletInsertingData,

whichmustextends theabstractHttpServletclass, thenameof theclassshouldbesuchthatotherpersoncanunderstandwhatthisprogramisgoingtoperform.Thelogicoftheprogram will be written inside the doGet() method that takes two arguments, first isHttpServletRequestinterfaceandthesecondoneistheHttpServletResponseinterfaceandthismethodcanthrowServletException.

InsidethismethodcallthegetWriter()methodofthePrintWriterclass.Wecaninsertthedatainthedatabaseonlyandonlyifthereisaconnectivitybetweenourdatabaseandthejavaprogram.ToestablishtheconnectionbetweenourdatabaseandthejavaprogramwefirstneedtocallthemethodforName(),whichisstaticinnatureoftheclassClass.Ittakesoneargumentwhichtellsaboutthedatabasedriverwearegoingtouse.Nowusethestatic method getConnection() of the DriverManager class. This method takes threeargumentsandreturnstheConnectionobject.SQLstatementsareexecutedandresultsarereturnedwithin thecontextofaconnection.Nowyourconnectionhasbeenestablished.Now use the method createStatement() of the Connection object which will return theStatementobject.Thisobject isusedforexecutingastaticSQLstatementandobtainingtheresultsproducedbyit.Wehavetoinsertavaluesintothetablesoweneedtowriteaquery for inserting the values into the table. This query we will write inside theexecuteUpdate()methodoftheStatementobject.Thismethodreturnsintvalue.

If the record will get inserted in the table then output will show “record has beeninserted”otherwise“sorry!Failure”.

SessionAsessionisaconversationbetweentheserverandaclient.Aconversationconsistsof

seriesofcontinuousrequestandresponse.

When there is a series of continuous request and response from a same client to aserver,theservercannotidentifyfromwhichclientitisgettingrequests.BecauseHTTPisastatelessprotocol.

Whenthereisaneedtomaintaintheconversationalstate,sessiontrackingisneeded.

Page 119: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Forexample, ina shoppingcart applicationaclientkeepsonadding items intohis cartusingmultiplerequests.Wheneveryrequestismade,theservershouldidentifyinwhichclient’scarttheitemistobeadded.Sointhisscenario,thereisacertainneedforsessiontracking.

Solution is, when a client makes a request it should introduce itself by providinguniqueidentifiereverytime.Therearefivedifferentmethodstoachievethis.

Sessiontrackingmethods:1. Userauthorization2. Hiddenfields3. URLrewriting4. Cookies5. SessiontrackingAPI

CookiesAlsoknownasbrowsercookiesortrackingcookies,cookiesaresmall,oftenencrypted

text files, located inbrowserdirectories.Theyareusedbywebdevelopers tohelpusersnavigatetheirwebsitesefficientlyandperformcertainfunctions.Duetotheircoreroleofenhancing/enablingusabilityorsiteprocesses,disablingcookiesmaypreventusersfromusingcertainwebsites.

Cookies are created when a user’s browser loads a particular website. The websitesendsinformationtothebrowserwhichthencreatesatextfile.Everytimetheusergoesbacktothesamewebsite,thebrowserretrievesandsendsthisfiletothewebsite’sserver.ComputerCookies are created not just by thewebsite the user is browsing but also byotherwebsites that runads,widgets,orotherelementson thepagebeing loaded.Thesecookiesregulatehowtheadsappearorhowthewidgetsandotherelementsfunctiononthepage.

CookieClassInJSPcookieistheobjectoftheclassjavax.servlet.http.Cookie.Thisclassisusedto

createacookie,asmallamountofinformationsentbyaservlettoaWebbrowser,savedbythebrowser,andlatersentbacktotheserver.Acookie’svaluecanuniquelyidentifyaclient, so cookies are commonlyused for sessionmanagement.Acookiehas aname, asingle value, and optional attributes such as a comment, path and domain qualifiers, amaximumage,andaversionnumber.

The getCookies() method of the request object returns an array of Cookie objects.Cookiescanbeconstructedusingthefollowingcode:

Cookie(java.lang.Stringname,java.lang.Stringvalue)

PRACTICAL14:WRITEASIMPLESERVLETPROGRAMWHICH

MAINTAINSACOUNTERFORTHENUMBEROFTIMESITHASBEEN

Page 120: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

ACCESSEDSINCEIT’SLOADING;INITIALIZETHECOUNTERUSINGDEPLOYMENTDESCRIPTOR.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnhowtouseSERVLETtomaintainhitofwebpages.

LEARNINGOUTCOMESUnderstandtheservletinitializationparametersusingweb.xmlfile.

ASSUMPTIONSOracleJDKinstalled,ApacheWebServerinstalledandconfigured.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,path,classpathareconfigured.

CODE

Index.html

<html>

<head>

<title>HitCounterusingSession</title>

</head>

<body>

<formid=“HitDemo”action=”/pagehit/PageHitCounter”method=“GET”>

<label>ClicktotestHitCounterforServlet</label>

<br><br>

<inputtype=submitvalue=“Submit”>

</form>

</body>

</html>

PageHitCounter.java

importjava.util.Enumeration;

importjavax.servlet.*;

importjavax.servlet.http.*;

importjavax.servlet.ServletException;

importjavax.servlet.ServletRequest;

Page 121: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

importjavax.servlet.ServletResponse;

importjavax.servlet.ServletConfig;

publicclassPageHitCounterextendsHttpServlet{

privateinthitCount;

publicvoidinit(ServletConfigservletConfig)throwsServletException{

this.hitCount=Integer.valueOf(servletConfig.getInitParameter(“hit”));

}

publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException

{

//Setresponsecontenttype

response.setContentType(“text/html”);

//Thismethodexecuteswhenevertheservletishit

//incrementhitCount

hitCount++;

PrintWriterout=response.getWriter();

Stringtitle=“TotalNumberofHits”;

StringdocType=

“<!doctypehtmlpublic“-//w3c//dtdhtml4.0“+

“transitional//en”>\n”;

out.println(docType+

“<html>\n”+

“<head><title>”+title+”</title></head>\n”+

“<bodybgcolor=”#f0f0f0”>\n”+

“<h1align=“center”>”+title+”</h1>\n”+

“<h2align=“center”>”+hitCount+”</h2>\n”+

“</body></html>”);

}

publicvoiddestroy()

{

//Thisisoptionalstepbutifyoulikeyou

//canwritehitCountvalueinyourdatabase.

Page 122: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

}

}

web.xml

<?xmlversion=“1.0”encoding=“UTF-8”?>

<web-app>

<servlet>

<servlet-name>PageHitCounter</servlet-name>

<servlet-class>PageHitCounter</servlet-class>

<init-param>

<param-name>hit</param-name>

<param-value>0</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>PageHitCounter</servlet-name>

<url-pattern>/PageHitCounter</url-pattern>

</servlet-mapping>

</web-app>

OUTPUT

PRACTICAL15:CREATEAFORMPROCESSINGSERVLETWHICH

DEMONSTRATESUSEOFCOOKIES.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

Learnhowtousecookieinservlettotracksessions.

LEARNINGOUTCOMESUnderstandtheuseofcookieforsessiontracking.

ASSUMPTIONSOracleJDKinstalled,ApacheWebServerinstalledandconfigured.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,path,classpathareconfigured.

Page 123: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

CODE

index.html

<html>

<head>

<title>CookiesExampleinServlets</title>

</head>

<bodybgcolor=wheat>

<center>

<h1>CookiesExampleinJava</h1>

<formaction=“CookieExample”method=“Post”>

Firstname:<inputtype=“text”name=“fname”>

Lastname:<inputtype=“text”name=“lname”>

<inputtype=“submit”value=“SUBMIT”>

</form>

</center>

</body>

</html>

CookieExample.java

importjavax.servlet.*;

importjavax.servlet.http.*;

importjava.io.*;

publicclassCookieExampleextendsHttpServlet

{

publicvoiddoPost(HttpServletRequestreq,HttpServletResponseres)throwsServletException,IOException

{

Stringfname=req.getParameter(“fname”);

Stringlname=req.getParameter(“lname”);

Cookief=newCookie(“first_name”,fname);

Cookiel=newCookie(“last_name”,lname);

Page 124: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

res.addCookie(f);

res.addCookie(l);

res.setContentType(“text/html”);

PrintWriterout=res.getWriter();

out.print(“<ahref=‘GetCookie’>CookiesCreatedSuccessfully!!!ClicktoReadcookies</a>”);

}

}

GetCookie.java

importjavax.servlet.*;

importjavax.servlet.http.*;

importjava.io.*;

publicclassGetCookieextendsHttpServlet

{

publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throwsServletException,IOException

{

PrintWriterpw=res.getWriter();

pw.println(“<h1>”);

Cookie[]c=req.getCookies();

for(Cookiek:c)

{

pw.println(k.getValue());

}

pw.println(“</h1>”);

}

}

Web.xml

<web-app>

<servlet>

<servlet-name>CookieExample</servlet-name>

<servlet-class>CookieExample</servlet-class>

Page 125: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</servlet>

<servlet-mapping>

<servlet-name>CookieExample</servlet-name>

<url-pattern>/CookieExample</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>GetCookie</servlet-name>

<servlet-class>GetCookie</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>GetCookie</servlet-name>

<url-pattern>/GetCookie</url-pattern>

</servlet-mapping>

</web-app>

OUTPUT

PRACTICAL16:CREATEAFORMPROCESSINGSERVLETWHICH

DEMONSTRATESUSEOFSESSIONS.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

Learnhowtousesessioninservlettotracksessions.

LEARNINGOUTCOMESUnderstandtheuseofsessionforsessiontracking.

ASSUMPTIONSOracleJDKinstalled,ApacheWebServerinstalledandconfigured.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,path,classpathareconfigured.

CODE

index.htm

<html>

<head>

Page 126: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<title>GetaHi!!!</title>

</head>

<body>

<formaction=“SessionExample”method=“get”>

<inputtype=“text”name=“user”/>

<inputtype=“submit”value=“Get”/>

</form>

</body>

</html>

Web.XMl

<web-app>

<servlet>

<servlet-name>SessionExample</servlet-name>

<servlet-class>SessionExample</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SessionExample</servlet-name>

<url-pattern>/SessionExample</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>SessionTrack</servlet-name>

<servlet-class>SessionTrack</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SessionTrack</servlet-name>

<url-pattern>/SessionTrack</url-pattern>

</servlet-mapping>

</web-app>

SessionExample.java

importjavax.servlet.*;

Page 127: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

importjavax.servlet.http.*;

importjava.io.*;

publicclassSessionExampleextendsHttpServlet

{

publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throwsServletException,IOException

{

Stringst=req.getParameter(“user”);

HttpSessionses=req.getSession();

ses.setAttribute(“uname”,st);

res.setContentType(“text/html”);

PrintWriterout=res.getWriter();

out.print(“<ahref=‘SessionTrack’>SessionCreatedSuccessfully!!!ClicktoReadSession</a>”);

}

}

SessionTrack.java

importjavax.servlet.*;

importjavax.servlet.http.*;

importjava.io.*;

publicclassSessionTrackextendsHttpServlet

{

publicvoiddoGet(HttpServletRequestreq,HttpServletResponseres)throwsServletException,IOException

{

PrintWriterpw=res.getWriter();

HttpSessionses=req.getSession();

Stringst=(String)ses.getAttribute(“uname”);

pw.println(“<h1>Hi“+st+”</h1>”);

}

}

OUTPUT

Page 128: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29
Page 129: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

UNIT5

GENERALOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

LearnhowtouseJSPtodevelopwebapplications.

DevelopanddeployaJSPapplicationusingApachewebserver.

LEARNINGOUTCOMESExplainJSPconcepts

PracticeJSPprograms.

ASSUMPTIONSOracleJDKinstalled,ApaheWebServerinstalled,configuredandrunning.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment

EnvironmentvariableslikeJAVA_Home,Path,Classpathareconfigured.

INTRODUCTIONJavaServerPages(JSP)isaJavatechnologythatallowssoftwaredevelopersto

dynamicallygenerateHTML,XMLorothertypesofdocumentsinresponsetoaWebclientrequest.ThetechnologyallowsJavacodeandcertainpre-definedactionstobeembeddedintostaticcontent.

TheJSPsyntaxaddsadditionalXML-liketags,calledJSPactions,tobeusedtoinvokebuilt-infunctionality.Additionally,thetechnologyallowsforthecreationofJSPtaglibrariesthatactasextensionstothestandardHTMLorXMLtags.

TaglibrariesprovideaplatformindependentwayofextendingthecapabilitiesofaWebserver.

JSPsarecompiledintoJavaServletsbyaJSPcompiler.AJSPcompilermaygenerateaservletinJavacodethatisthencompiledbytheJavacompiler,oritmaygeneratebytecodefortheservletdirectly.

JSPtechnologyenablesWebdevelopersanddesignerstorapidlydevelopandeasilymaintain,information-rich,dynamicWebpagesthatleverageexistingbusinesssystems.AspartoftheJavatechnologyfamily,JSPtechnologyenablesrapiddevelopmentofWeb-basedapplicationsthatareplatformindependent.

JSPtechnologyseparatestheuserinterfacefromcontentgeneration,enabling

Page 130: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

designerstochangetheoverallpagelayoutwithoutalteringtheunderlyingdynamiccontent

CreateandRunasimpleJSPprogramusingtomcatHereIamgoingtoexplainforwritecreateasimplejspprogramandrunthatprogram

inapachetomcat.Thisprocesshassomesteps.Thefollowingstepsarebasedonwindowsoperatingsystem

JavaServerPagesaresavedwith.jspextension.

InstallationandexecutionofJSP

FollowthesestepstorunJSPPage:

Step1:DownloadandinstalllatestApacheTomcatandJAVA.

Step 2: Create directory “JSPDemo” and apache D:\apache-tomcat-8.0.15\webapps\JSPDemodirectoriesunderthewebappsasshownhere:

Step3:CreatesimpleHelloWorld.jspprogramusinganyeditorlikenotepad:

<%@pagecontentType=“text/html”pageEncoding=“UTF-8”%>

<html>

<head>

<title>FirstJSPPage</title>

</head>

<body>

<p>Hi,<h3><%=“Hello!”%></h3></p>

</body>

</html>

Step 4:SavethisfileasHelloWorld.jspinD:\apache-tomcat-8.0.15\webapps\JSPDemo\JSPAppdirectory:

Page 131: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Step5:Beforerunthiscode,startapachetomcatasyouhavedonefollowingSection.

ApacheTomcatportinformation

Iamgivingthefollowinginformation1.Tomcatportinformation2.ChangeTomcatusernameandpassword(optional)3.Start,StopandRestarttomcat

1.Tomcatportinformation

D:/…/Tomcat6.0/conf/server.xml

This file havedefault port number (During installation specified…)you can able tochangethatportnumber.Server.xml

<?xmlversion=‘1.0’encoding=‘utf-8’?>

<Serverport=“8005”shutdown=“SHUTDOWN”>

<Connectorport=“9999”protocol=“HTTP/1.1”connectionTimeout=“20000”

redirectPort=“8443”/>

</Server>

Page 132: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

Theconnectortagshaveyourtomcatportnumber.

2.Changethetomcatmangerusernameandpassword.(optional)

Ifyouwant tochange the tomcatusernameandpassword, thenyouedit the tomcat-user.xmlfile

<tomcat-users>

<rolerolename=“admin”/>

<rolerolename=“manager”/>

<rolerolename=“tomcat”/>

<rolerolename=“role1”/>

<userusername=“admin”password=“admin123”roles=“admin,manager”/>

<userusername=“tomcat”password=“tomcat”roles=“tomcat”/>

<userusername=“both”password=“tomcat”roles=“tomcat,role1”/>

<userusername=“role1”password=“tomcat”roles=“role1”/>

</tomcat-users>

HereIshowed,changedtomcatadminusernameandpassword

Theusername:adminThepassword:admin123

3.Start,StopandResarttomcat

Ifyouhavechange(server.xmlor tomcat-user.xml), thenbetteryouwill restartyourtomcat.

Start or Restart (if already running) Apache Tomcat Server from command lineD:\apache-tomcat-8.0.15\bin>startup.

Page 133: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

4:Checkyourusernameandpassword(optional)

http://localhost:9999/

ThenClickTomcatManagerandgiveusername(admin)andpassword(admin123).Ifsuccessfullylogin,thenusernameandpasswordperfecltlyset.Otherwise,checktomcat-users.xmlfile.

Step6:Setpath, java_home,andclasspathvariableasrequiredfromcommandline.Forexample:

SetJAVA_HOME=C:\ProgramFiles\Java\jdk1.8.0_25\

setPATH=%JAVA_HOME%;%PATH%

setCLASSPATH=.;D:\apache-tomcat-8.0.15\lib\jsp-api.jar;D:\apache-tomcat-8.0.15\webapps\JSPDemo; C:\Program Files\Java\jdk1.8.0_25\jre\lib\ext\ mysql-

connector-java-5.1.34-bin;%classpath%Step7:RunHelloWorld.jspprograminbrowserusingfollowinglink:

http://localhost:9999/JSPDemo/HelloWorld.jsp

Step8:Observetheoutput:

Page 134: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

PRACTICAL17:WRITEASIMPLEJSPPROGRAMFORUSERREGISTRATION&THENCONTROLWILLBETRANSFERITINTOSECONDPAGE.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopaJSPPrograminJAVA.

LearnHowtohandlepageredirectinginWebbrowser.

LEARNINGOUTCOMESExplain&PracticeJspscriplettagsandHTMLtags.

ASSUMPTIONSOracleJDK,Apache-tomcat-8.0.15installed.

EditorLikenotepad,Netbeansavailableforprogramdevelopment.

EnvironmentvariableslikeJAVA_Home,Path,andClasspathareconfigured.

CODE

Registration.jsp

<%@pagelanguage=“java”contentType=“text/html;charset=UTF-8”

pageEncoding=“UTF-8”%>

Page 135: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<html>

<head>

<title>RegistrationForm</title>

</head>

<body>

<h1align=“center”>

<b>REGISTRATIONFORM</b>

</h1>

<formaction=“welcome.jsp”method=“post”>

<div>

<labelfor=“inputFirstname”>FirstName

</label>

<div>

<inputtype=“text”name=“firstname”maxlength=“12”

placeholder=“firstname”></input>

</div>

</div>

<div>

<labelfor=“inputLastname”>LastName

</label>

<div>

<inputtype=“text”name=“lastname”maxlength=“12”

placeholder=“lastname”></input>

</div>

</div>

<div>

<labelfor=“inputMobile”>Mobile</label>

<div>

<inputtype=“text”name=“mobile”maxlength=“10”

placeholder=“Ex:95xxxx4104”></input>

</div>

Page 136: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</div>

<div>

<labelfor=“inputEmail”>E-mail</label>

<div>

<inputtype=“text”name=“email”maxlength=“50”

placeholder=“[email protected]”></input>

</div>

</div>

<div>

<labelfor=“gender”>Gender</label>

<div>

<inputtype=“radio”name=“optionsRadios”id=“optionsRadios1”

value=“Male”checked>Male<inputtype=“radio”

name=“optionsRadios”id=“optionsRadios2”value=“Female”>Female

</div>

</div>

<div>

<labelfor=“inputAddress”>Address</label>

<div>

<inputtype=“text”name=“address”maxlength=“70”id=“address”

placeholder=“Address”></input>

</div>

</div>

<div>

<labelfor=“inputCity”>City</label>

<div>

<input type=“text” name=“city” id=“city” placeholder=“Noida”></input>

</div>

</div>

<div>

<labelfor=“inputState”>State</label>

Page 137: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<div>

<inputtype=“text”id=“state”name=“state”id=“state”

placeholder=“Delhi”></input>

</div>

</div>

<div>

<div>

<inputtype=“reset”value=“Reset”/><input

type=“submit”value=“Submit”/>

</div>

</div>

</form>

</body>

</html>

</body>

</html>

welcome.jsp

<%@pagelanguage=“java”contentType=“text/html;charset=UTF-8”

pageEncoding=“UTF-8”%>

<html>

<head>

<title>DetailsOfUser</title>

</head>

<body>

<h3>

<left>

<i>REGISTRATIONHASBEENCOMPLETEDSUCCESSFULLY…….</i>

</left>

</h3><br>

FirstName:<%=request.getParameter(“firstname”)%><br>

LastName:<%=request.getParameter(“lastname”)%><br>

Page 138: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

email:<%=request.getParameter(“email”)%><br>

mobile:<%=request.getParameter(“mobile”)%><br>

city:<%=request.getParameter(“city”)%><br>

State:<%=request.getParameter(“state”)%><br>

Gender:<%=request.getParameter(“optionsRadios”)%><br>

address:<%=request.getParameter(“address”)%>

</body>

</html>

OUTPUT

PRACTICAL18:WRITEASIMPLEJSPPROGRAMFORUSERLOGINFORMWITHSTATIC&DYNAMICDATABASE.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopaJSPPrograminJAVA.

LearnHowtohandlestaticanddynamicdatabaseinWebbrowser.

LEARNINGOUTCOMESExplain&PracticehowtoaccessmysqldatabasefromJSPprogramme.

ASSUMPTIONSOracleJDK,Apache-tomcat-8.0.15andwampserver2.2c-x32installed.

EditorLikenotepad,Netbeansavailableforprogramdevelopment.

EnvironmentvariableslikeJAVA_Home,Path,andClasspathareconfiguredandcopymysql-connectorjarfiletofolderC:\ProgramFiles\Java\jdk1.8.0_25\jre\lib\ext.

CODE(A)

(a) WriteasimpleJSPprogramforuserloginformwithstaticdatabase.

Login.jsp

<html>

<head>

<title>JSPPage</title>

Page 139: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</head>

<body>

<h1><center>LoginPage</center></h1>

<center>

<h2>SignupDetails</h2>

<formaction=“logincheck.jsp”method=“post”>

<br/>Username:<inputtype=“text”name=“username”>

<br/>Password:<inputtype=“password”name=“password”>

<br/><inputtype=“submit”value=“Submit”>

</form>

</center>

</body>

</html>

Logincheck.jsp

<html>

<head>

<title>JSPPage</title>

</head>

<body>

<%

Stringusername=request.getParameter(“username”);

Stringpassword=request.getParameter(“password”);

if((username.equals(“kdp”)&&password.equals(“kdp123”)))

{

session.setAttribute(“username”,username);

response.sendRedirect(“home.jsp”);

}

else

response.sendRedirect(“error.jsp”);

%>

</body>

Page 140: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</html>

Home.jsp

<%@page contentType=“text/html” pageEncoding=“UTF-8”errorPage=“Error.jsp”%>

<html>

<head>

<title>JSPPage</title>

</head>

<body>

<br/><br/><br/><br/><br/>

<center>

<h2>

<%

Stringa=session.getAttribute(“username”).toString();

out.println(“Hello“+a);

%>

</h2>

<br/>

<br/>

<br/><br/><br/><br/><br/>

<ahref=“logout.jsp”>Logout</a>

</center>

</body>

</html>

Logout.jsp

<%@pagecontentType=“text/html”pageEncoding=“UTF-8”%>

<html>

<head>

<title>JSPPage</title>

</head>

<body>

Page 141: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<%

session.removeAttribute(“username”);

session.removeAttribute(“password”);

session.invalidate();

%>

<h1>Logoutwasdonesuccessfully.</h1>

</body>

</html>

Error.jsp

<%@pagecontentType=“text/html”pageEncoding=“UTF-8”%>

<html>

<head>

<title>JSPPage</title>

</head>

<body>

<h1>SorryInvalidUsernameorPassword…</h1>

</body>

</html>

OUTPUT

CODE(B)

(b) WriteasimpleJSPprogramforuserloginformwithdynamicdatabase.

->CreatelogindatabaseDatabaseinMySQL.

->CreatemembersTableunderlogindatabaseDatabase.

Members:

first_name last_name email uname pass regdate

login.jsp

Page 142: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<%@pagecontentType=“text/html”pageEncoding=“UTF-8”%>

<html>

<head>

<title>JSPExample</title>

</head>

<body>

<formmethod=“post”action=“logincheck.jsp”>

<center>

<tableborder=“1”width=“30%”cellpadding=“3”>

<thead>

<tr>

<thcolspan=“2”>LoginHere</th>

</tr>

</thead>

<tbody>

<tr>

<td>UserName</td>

<td><inputtype=“text”name=“uname”value=””/></td>

</tr>

<tr>

<td>Password</td>

<td><inputtype=“password”name=“pass”value=””/></td>

</tr>

<tr>

<td><inputtype=“submit”value=“Login”/></td>

<td><inputtype=“reset”value=“Reset”/></td>

</tr>

<tr>

<tdcolspan=“2”>NotYetRegistered!!<ahref=“Newregistration.jsp”>RegisterHere</a></td>

</tr>

Page 143: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</tbody>

</table>

</center>

</form>

</body>

</html>

Logincheck.jsp

<%@pageimport=“java.sql.*”%>

<%

Stringuserid=request.getParameter(“uname”);

Stringpwd=request.getParameter(“pass”);

Class.forName(“com.mysql.jdbc.Driver”);

Connectioncon=DriverManager.getConnection(“jdbc:mysql://localhost/logindatabase”,

“root”,””);

Statementst=con.createStatement();

ResultSetrs;

rs=st.executeQuery(“select*frommemberswhereuname=’”+userid+”’andpass=’”+pwd+”’”);

if(rs.next()){

session.setAttribute(“userid”,userid);

response.sendRedirect(“success.jsp”);

}else{

out.println(“Invalidpassword<ahref=‘login.jsp’>tryagain</a>”);

}

%>

Newregistration.jsp

<%@pagecontentType=“text/html”pageEncoding=“UTF-8”%>

<html>

<head>

Page 144: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<title>Registration</title>

</head>

<body>

<formmethod=“post”action=“registrationsubmit.jsp”>

<center>

<tableborder=“1”width=“30%”cellpadding=“5”>

<thead>

<tr>

<thcolspan=“2”>EnterInformationHere</th>

</tr>

</thead>

<tbody>

<tr>

<td>FirstName</td>

<td><inputtype=“text”name=“fname”value=””/></td>

</tr>

<tr>

<td>LastName</td>

<td><inputtype=“text”name=“lname”value=””/></td>

</tr>

<tr>

<td>Email</td>

<td><inputtype=“text”name=“email”value=””/></td>

</tr>

<tr>

<td>UserName</td>

<td><inputtype=“text”name=“uname”value=””/></td>

</tr>

<tr>

<td>Password</td>

<td><inputtype=“password”name=“pass”value=””/></td>

Page 145: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</tr>

<tr>

<td><inputtype=“submit”value=“Submit”/></td>

<td><inputtype=“reset”value=“Reset”/></td>

</tr>

<tr>

<tdcolspan=“2”>Alreadyregistered!!<ahref=“login.jsp”>LoginHere</a></td>

</tr>

</tbody>

</table>

</center>

</form>

</body>

</html>

Registrationsubmit.jsp

<%@pageimport=“java.sql.*”%>

<%

Stringuser=request.getParameter(“uname”);

Stringpwd=request.getParameter(“pass”);

Stringfname=request.getParameter(“fname”);

Stringlname=request.getParameter(“lname”);

Stringemail=request.getParameter(“email”);

Class.forName(“com.mysql.jdbc.Driver”);

Connectioncon=DriverManager.getConnection(“jdbc:mysql://localhost/logindatabase”,

“root”,””);

Statementst=con.createStatement();

inti=st.executeUpdate(“insertintomembers(first_name,last_name,email,uname,pass,regdate)values(’”+fname+”’,’”+lname+”’,’”+email+”’,’”+user+”’,’”+pwd+”’,CURDATE())”);

if(i>0){

Page 146: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

response.sendRedirect(“welcome.jsp”);

}

else{

response.sendRedirect(“login.jsp”);

}

%>

Welcome.jsp

RegistrationisSuccessful.

PleaseLoginHere<ahref=‘login.jsp’>GotoLogin</a>

Success.jsp

<%

if((session.getAttribute(“userid”)==null)||(session.getAttribute(“userid”)==””)){

%>

Youarenotloggedin<br/>

<ahref=“login.jsp”>PleaseLogin</a>

<%}else{

%>

Welcome<%=session.getAttribute(“userid”)%>

<ahref=‘logout.jsp’>Logout</a>

<%

}

%>

OUTPUT:

Page 147: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

PRACTICAL19:WRITEAJSPPROGRAMTODISPLAYTHEGRADEOFASTUDENTBYACCEPTINGTHEMARKSOFFIVESUBJECTS.SPECIFICOBJECTIVES

Afterperformingthispracticalstudentwillbeableto:

DevelopaJSPPrograminJAVA.

LearnHowtohandlepageredirectinginwebbrowser.

LEARNINGOUTCOMESExplain&PracticeJspscriplettagsandHTMLtags.

ASSUMPTIONSOracleJDK,Apache-tomcat-8.0.15installed.

EditorLikenotepad,Jcreatoravailableforprogramdevelopment.

EnvironmentvariableslikeJAVA_Home,Path,andClasspathareconfigured.

CODE

<%@pagelanguage=“java”contentType=“text/html;charset=ISO-8859-1”

pageEncoding=“ISO-8859-1”%>

<html>

<head>

<title>StudentMarks</title>

</head>

<body>

<h2>StudentGradingSystem</h2>

<formaction=””method=“post”>

<table>

<tr>

<td></td>

<td>

EnterFiveSubjectMarksoutof100

</td>

Page 148: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

</tr>

</table>

<table>

<tr>

<th>Subject</th>

<th>ObtainedMarks</th>

<th>TotalMarks</th>

</tr>

<tr>

<tdalign=“center”>C</td>

<tdalign=“center”><inputtype=“text”size=“5”name=“c”/></td>

<tdalign=“center”>100</td>

</tr>

<tr>

<tdalign=“center”>Java</td>

<tdalign=“center”><inputtype=“text”size=“5”name=“java”/></td>

<tdalign=“center”>100</td>

</tr>

<tr>

<tdalign=“center”>.Net</td>

<tdalign=“center”><inputtype=“text”size=“5”name=“net”/></td>

<tdalign=“center”>100</td>

</tr>

<tr>

<tdalign=“center”>VB</td>

<tdalign=“center”><inputtype=“text”size=“5”name=“vb”/></td>

<tdalign=“center”>100</td>

</tr>

<tr>

<tdalign=“center”>DBMS</td>

<tdalign=“center”><inputtype=“text”size=“5”name=“dbms”/></td>

Page 149: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

<tdalign=“center”>100</td>

</tr>

<tr>

<td></td>

</tr>

<tr>

<td></td>

</tr>

<tr><td></td><tdalign=“center”><inputtype=“submit”value=“submit”/></td></tr>

</table>

</form>

<%

Stringc=request.getParameter(“c”);

Stringj=request.getParameter(“java”);

Stringn=request.getParameter(“net”);

Stringv=request.getParameter(“vb”);

Stringd=request.getParameter(“dbms”);

if(!(c==null||c.isEmpty()))

{

intcmarks=Integer.parseInt(c);

intjmarks=Integer.parseInt(j);

intnmarks=Integer.parseInt(n);

intvmarks=Integer.parseInt(v);

intdmarks=Integer.parseInt(d);

inttotal=cmarks+jmarks+nmarks+vmarks+dmarks;

intavg=(total)/5;

intpercent=avg;

Stringgrade=””;

if(percent<40){

Page 150: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

grade=“E”;

//request.setAttribute(“grade”,grade);

}

elseif(percent>=40&&percent<=44){

grade=“D”;

}

elseif(percent>=45&&percent<=49){

grade=“D+”;

}

elseif(percent>=50&&percent<=54){

grade=“C-“;

}

elseif(percent>=55&&percent<=59){

grade=“C”;

}

elseif(percent>=60&&percent<=64){

grade=“C+”;

}

elseif(percent>=65&&percent<=69){

grade=“B-“;

}

elseif(percent>=70&&percent<=74){

grade=“B”;

}

elseif(percent>=75&&percent<=79){

grade=“B+”;

}

elseif(percent>=80&&percent<=84){

grade=“A”;

}

elseif(percent>=85&&percent<=100){

Page 151: Osmora.advanced JAVA Laboratory Manual.2016%28epub%29

grade=“A+”;

}

request.setAttribute(“Grade”,grade);

%>

<table>

<tr>

<td><b>AggregateMarks</b></td><td></td>

<tdalign=“center”><%=total%></td>

</tr>

<tr>

<td><b>Grade</b></td><td></td>

<tdalign=“center”><%=grade%></td>

</tr>

</table>

<%

}

%>

</body>

</html>

OUTPUT