Tải bản đầy đủ - 0 (trang)
Chapter 20. GUI Basics and Event Handling

Chapter 20. GUI Basics and Event Handling

Tải bản đầy đủ - 0trang

Ddrawinglibrary,similartotheonesinJava.

Forthefirstcoupleofmajorreleases,JavasupportedGUI

operationswithapackagecalledjava.awt.The"AWT"stands

for"AbstractWindowToolkit."TheAWTsupportedthe

portabilitygoalsofJava.Thetoolkitgaveuserprogramsa

commonbinarywindowinterfaceonsystemswithdifferent

nativewindowsystems.That'saveryunusualfeature,like

havingyourfavoriteMacintoshprogramrunonaWindowsPC

andstilldoGUIoperations.Youmightwonderhowitisdone.

YoucancallmethodsintheAWTrun-timetopopupanative

menu,resizeawindow,getthelocationofamouseclick,and

soon.JavathencallsthroughtothenativeGUIlibrary.Events

comingbackfromtheGUIgointotheJavarun-time,andare

passedontoyourcodeasappropriate.TheJavabytecodeis

thesameoneachplatform,butthenativelibrarybehindthe

Javarun-timelibraryisspecifictoeachplatform.TheAWTcode

usestheunderlyingnative(or"peer")windowsystemto

manipulateGUIobjects.

TheAWTisaseriesofabstractinterfacesalongwithJavacode

tomapthemintotheactualnativecodeoneachsystem.Thisis

whyitisanabstractwindowtoolkit:itisnottailoredfora

specificcomputer,butitoffersthesameAPIonall.Toomuch

differentnativebehaviorleakedthroughand,eventuallyIBM

persuadedSuntomovetoanall-JavaGUIknownasSwing.

SwingisalmostwhollyimplementedinJava.Itusesnative

canvasesonwhichtodisplaywidgetscontrolledanddrawnby

Java.

WementionedthelistofservicesthatanyGUIlibrarymust

support.Thischapterfocusesononeoftheseservices:an

event-handlingsystemthatnoticeswhentheuseradjustsone

ofthecomponentsandinterruptstheprogramtotellitwhat

happened.

Youmustknowhowtohandletheeventsthatcontrolscan



generatebeforeyoucanmakesenseofthecontrols

themselves.Eventhandlingisadullbutnecessaryprerequisite,

likeeatingyourvegetablesbeforeyoucanhavedessert.Wewill

dealwithcontrolsinthenextchapter.ThebasicideawithJava

GUIprogramsisthatyoudothefollowingactions:

1. Declarecontrols.Thesecontrolsincludebuttons,menus,

andchoices.Youcanextendtheseclassestoaddyourown

ideas/needstothebehavior,butthisisoftenunnecessary.

2. Implementeventhandlerstorespondtoclicking,menu

selection,buttonpresses,windowre-sizingandother

activity.Yourimplementingclasswilloftenbean

anonymousclass.Usingananonymousclassreducesthe

amountofcodeandputstheclassdeclarationcloseto

whereitisused.

3. Addthecontrolstoacontainer.Youmaychoosetoextend

thecontainerclass,butthisisfrequentlyunnecessary.

Containersdisplayonthescreen.Containerscanhold

severalrelatedcontrolsthatyouwanttoappearnextto

eachotheronscreen.Forexample,aframecanholdtwo

buttonsandascrollingpanel.

It'sachallengetoexplainallthis.Thefirstthreetopicsdeclaring

controls,handlingtheirevents,andputtingthemin

containersfittogethersocloselythatyouhavetounderstanda

bitofeachbeforeyoucanfullyunderstandanyofthem.The

topicsaresobigthateachrequiresawholechapter,andwewill

takethemserially.



AllAboutEventHandling

First,afewnecessarywordsofexplanationaboutthe

programmingmodelforwindowsystems.Unlikeprocedural

programsinwhichthingshappensequentially,windowing

programsareasynchronous,becauseactionsoccurat

unpredictabletimes.Youneverknowwhichoftheonscreen

buttons,menus,frames,orotherelementstheuserwilltouch

next.Accordingly,amodelknownasevent-drivenprogramming

isused.

Inevent-drivenprogramming,thelogicofyourcodeisinverted.

Insteadofoneflowofcontrolfrombeginningtoend,theruntimesystemsitsina"windowmainloop"simplywaitingfor

userinput.Whentheuserclicksthemouse,theoperating

systempassesittothewindowmanagerwhichturnsitintoan

eventandpassesitontoahandleryousuppliedearlier.Thisis

knownasacallback.Yourhandlerisacallbackroutine,because

thewindowsystemcallsbacktoitwhentheeventhappens.

Youreventhandlerdealswiththegraphicseventandanywork

associatedwithit.

Ifabuttonsays"pressheretoreadthefile,"yourcodemust

arrangeforthefiletobereadwhencalled.Handlingabutton

eventmeansnoticingthatitoccurredanddoingtheassociated

action,butothereventsmayinvolvesomedrawingonthe

screen.Forexample,draggingsomethingwiththemouseisjust

repeatedlydrawingitunderthemousecoordinatesasitmoves.



Javaeventmodel

Theeventmodelisthenamefortheframeworkthatturnsa

GUIinteraction(mouseclick,menuselection,buttonpress,

etc.)intoacallforyourcodetoprocessit.Theeventmodelcan



alsobeusedforsomethingunrelatedtotheGUI,likeatimer

goingoff.Inotherwords,theeventmodelisthedesignfor

connectingyourcodetoanykindofasynchronousactions,

calledevents,forhandling.

Thewindowmanagercan'tdirectlycallyourevent-handling

routinesbecausetherun-timelibrarydoesn'tevenseeyour

codeuntilitisaskedtorunit.Therefore,atrun-timetheevent

modelhastobetoldwhichofyourroutineshandleevents.

Javaoriginallyusedinheritancetotietogetheryourcodeand

theeventmodel.JDK1.1introducedabetterapproachcalled

thedelegation-basedmodel.SomeoftheJavadocumentation

stillrefersto"1.1-styleevents,"whichisthecurrentmodel.To

getanyevents,yourcodehastobeginbytellingthewindow

system,"sendthoseeventsofyourstothesemethodsofmine".

Youconnectthecontrolsthatgenerateeventsbyregisteringa

callbackwithyourevent-handlingclasses,asFigure20-1

shows.



Figure20-1.HoweventsarepassedinJDK1.1



[Viewfullsizeimage]



Threads,theeventdispatcher,andyourcode

YouwillnoticethatonceyouputaGUIcomponentonscreen,yourprogramdoes

notendwhenitreachestheendofthemain()method.Thisisnotanewruleit's

thesameoldruleaboutaprogramnotendingwhileitstillhasoneormore

threadsrunning.

WhenyoumakeaGUIcomponentvisible,athreadisstartedinsidetheJava

run-timelibrarytoreceiveeventsthatmaybegeneratedbythatcomponent.

TheunderlyingOSwindowsystemlibraryistoldtopassalleventstothisJava

run-timelibrarythread,andthisthreadisresponsibleforforwardingtheevents

ontoyourcode.Thefactthatthiseventthreadislivepreventsyourprogram

fromexitingwhenitfallsofftheendofmain().SotheGUIstaysonthescreen,

andtheprogramnowrunsinresponsetouserinputontheGUI.

ThisJavalibrarythreadiscalledthe"eventdispatchingthread."Itrunsinyour

addressspace,inparallelwithallyourcode,butspendsmostofitstimeblocked

waitingforaGUIevent.WhenaGUIeventoccurs,theeventdispatchingthread

eitherconsumestheeventitself,orcallsbacktotheevent-handlercodethatyou

wroteandregistered.

Therefore,youreventhandlersareexecutedbyoneoftheJavarun-timelibrary

threads,notbyoneofyourthreads!Oneimplicationofthisisthatyourevent

handlerswillblockthedeliveryofotherGUIevents,andsomustbebriefand

quicktoexecute.Youneverwanttoundertakeatime-consumingoperationlike

readingafileinaneventhandler.Instead,spawnitoffintoathreadofitsown.

Youcandothiswithaninner(ornot)classinyoureventhandler,andgetitto

runlikethis:



newThread(){//runitinadifferentthreadtoeventhandler

publicvoidrun(){

//putyourlengthynon-GUIstatementshere

}

}.start();



Conversely,thereisastaticmethodintheSwingUtilitiesclassthatwilltakea



Runnableobjectandexecuteitlaterintheeventhandlerthread.AnyandallGUI

adjustmentsyouwanttomakeaftertheGUIfirstbecomesvisible,mustbedone

intheeventhandlerthread.Weshowanexampleofthisinthenextchapter.

GUIeventsareautomaticallyaddedtoaqueueintherun-timelibraryasthey

happen.Theeventdispatchingthreademptiesthisqueuebydispatchingthe

eventstoyourhandlercode.

Sincealleventdispatchingishandledbyonelibrarythreadalone,another

implicationisthatthelibrarycandolesssynchronizationthanwouldberequired

ifmanythreadswererunning.Lesssynchronizationequalsbetteroverall

performance,aslongasthesynchronizationisstillcorrect.



YouregisteryourhandlercodeonceatthebeginningwiththeGUI

objectthatwillbegeneratingevents.Afterthat,thoseeventsare

fired(orsent)toyouwhentheyoccur.Inparticular,yourhandler

codeiscalledandpassedtheeventobjectasanargument.



Ifyoudonotcompletelyunderstandcallbacks,gobackand

readthatsectioninChapter11.Itisessentialthatyou

understandcallbacksbecausetheyformthebasisofthenew

event-handlingmodel.

Theeventsthatarefiredfromthesourcetothelistenerare

simplyobjectspassedasargumentstoamethodcall.Anevent

objecthasseveraldatafieldsholdinginformation,suchas

wheretheeventtookplaceonthescreen,adescriptionofthe

event,thenumberofmouseclicks,thestateofacheckbox,and

soon.Thereisageneraljava.util.EventObjecttypeandallAWT

eventsarechildrenofthat,asFigure20-2shows.



Figure20-2.ThehierarchyofeventobjectsinJDK

1.1



TheJFrameexample

AJFrame,asubclassoftheAWTclassFrame,hasatitlestring

andamenubaronwhichyoucanaddseveralmenus.Following

isthecodetoputaJFrameonthescreenfromanapplication:



importjavax.swing.*;

publicclassFrameDemo{

publicstaticvoidmain(String[]args){

JFramejframe=newJFrame("Example");

jframe.setSize(400,100);

jframe.setVisible(true);

}

}



Compilingandexecutingthisprogramresultsinaframesimilar

toFigure20-3toappearonthescreen.Here,wejustgaveit

thenameonthetitlebarof"Example."



Figure20-3.TheJFrameisasubclassofFrame,

whichisasubclassofWindow



SinceitisaWindow,JFrameiscapableofreceivingevents



generatedbyWindows.ClickingaWindowtocloseitgenerates

anevent.Ifyoutrythiswiththeprogramwedescribed,you'll

noticethattheJFramegoesawaybutyourprogramstays

active.YoumustpressControl-Ctoexittheprogrambecause

youneedtowritecodetohandlethe"windowclosing"event.

Thecodeshouldquittheprogramwhenitisinvoked.

Let'saddaneventhandlertoourJFramethatnoticeswhenthe

WindowClosingeventtakesplace.Thateventwillbedelivered

whenyouclicktocloseaWindow.

First,tellourJFramethatWindoweventsarehandledbyan

objectthatIcall"mwh"hereaniceshortnamewhichisan

abbreviationof"mywindowhandler."Thecodeappearsexactly

asbefore,andweaddthefollowinglinetothemain()routine:



jframe.addWindowListener(mwh);



ThecallbackforaWindoweventisregisteredbycallingthe

AWTmethodaddWindowListener.Thisisamethodinthe

WindowsuperclassofJFramethattakesasaparameteran

interfacecalledWindowListener.Yourappletmustdeclarean

instanceofaclassthatimplementstheWindowListener

interfaceandthatwillbetheeventhandlerforthisbutton.You

stillhavetowritethatclass,butassumingithasthename

shownbelow,youcaninstantiateanobjectaccordingtothe

followingexample:



myCodeToHandleWinClosemwh=newmyCodeToHandleWinClose();



ThelaststepistowritethemyCodeToHandleWinCloseclassthat

implementsthejava.awt.event.WindowListenerinterfaceand

providesthepromisedmethods.Theclasscanbeinaseparate

fileorcontainedinthesameone.



classmyCodeToHandleWinCloseimplementsWindowListener{



publicvoidwindowClosing(WindowEvente){System.exit(0);}

publicvoidwindowClosed(WindowEvente){}

publicvoidwindowOpened(WindowEvente){}

publicvoidwindowIconified(WindowEvente){}

publicvoidwindowDeiconified(WindowEvente){}

publicvoidwindowActivated(WindowEvente){}



publicvoidwindowDeactivated(WindowEvente){}

}



ThewindowClosing()methodofthemyCodeToHandleWinClose

classiscalledwhenevertheWindow"close"choiceismade.

Noticethatitwasnecessarytoprovidedeclarationsforallthe

routinesintheinterface.Sinceweareinterestedonlyin

WindowClosing,thereareemptybodiesfortheothermethods.

We'llshowawayofsimplifyingthislaterinthechapter.

TheWindowListenerinterface(likemanyofthe

SomethingListenerinterfaces)isdeclaredinthejava.awt.event

package.ThereareothereventandListenersdeclaredinthe

javax.swing.eventpackage.TheWindowListenerinterface

promisesthattherewillbehalfadozenmethodswithspecific

names.ThemethodswillbecalledfordifferentWindowevents

nowthatwehavedelegatedthetasktotheobject"mwh"that

containsthemethods.

OneadvantageoftheJavaeventframeworkisthattheGUIrelatedcodeiseasilyseparatedfromtheapplicationlogiccode.

ThisflowsfromgooduseofOOP:puteverythinginaclassofits

ownanddeclareinstancesoftheclassasneeded.Inthisway,

encapsulationworksforyou.Ifyouwanttochangewhat

happensonwindowclose,youjustupdatetheclassthatdeals

specificallywithit.Inanon-OOPimplementation,it'stooeasy

tomixeverythingtogether,makingprogrammaintenanceand

testingtentimesharderthanitshouldbe.Thesameevent

frameworkisusedforJavaBeans(componentsoftware),aswell

astheAWT.

PuttingthewholethingtogetherandintoourJFrameexample,



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 20. GUI Basics and Event Handling

Tải bản đầy đủ ngay(0 tr)

×