Tải bản đầy đủ - 0 (trang)
Chapter 4. The Standard Widget Toolkit

Chapter 4. The Standard Widget Toolkit

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

4.1.SWTHistoryandGoals

TherootsofSWTgobackmorethanadozenyearstoworkthat

ObjectTechnologyInternational,orOTI(thenanindependent

pioneeringOOsoftwarecompanyandnowapartofIBM),did

whencreatingmultiplatform,portable,nativewidgetinterfaces

forSmalltalk(originallyforOTISmalltalk,whichbecameIBM

Smalltalkin1993).IBMSmalltalk'sCommonWidget(CW)layer

providedfast,nativeaccesstomultipleplatformwidgetsets

whilestillprovidingacommonAPIwithoutsufferingthe"lowest

commondenominator"(LCD)problemtypicalofotherportable

graphicaluserinterface(GUI)toolkits.

Formanyyears,IBMhadbeenusingSmalltalkasits"secret

weapon"whenbuildingdevelopmenttools(evenIBM'sfirstJava

IDE,VisualAgeforJava,waswritteninSmalltalk);however,

Smalltalkhaddeploymentandconfigurationproblemsthat

ultimatelydoomeditslong-termuseatIBM.

Java'spromiseofuniversalportabilityandubiquitousvirtual

machines(VMs)oneverydesktopwasveryappealingtothe

folksatIBMresponsibleforcreatingthenextgenerationof

developmenttools.InJava,OTIalsosawanotherlanguageto

whichitcouldapplyitsmanytalents.

Sun'sinitialattemptatprovidingaportablewidgetAPI,the

AbstractWindowingToolkit(AWT),sufferedfrombothanoverly

complexinterfacetothenativewidgetsandtheLCDproblem.It

providedaccesstoaminimalsetofwidgets,suchasbuttons,

labels,andlists,commonacrossmostplatformsbutdidnot

provideaccesstoricherwidgetssuchastables,trees,and

styledtext.That,coupledwithananemicAPI,destineditto

failureinthemarketplace.

TosolvetheproblemsofAWTandtoprovideJavawithamore

powerful,extensibleGUIlibrary,Sundecidedtoabandonnative



widgetinterfacesanddevelopeditsownportable,emulated

widgetlibraryofficiallyknownastheJavaFoundationClasses

(JFC)morecommonlyknownasSwing.Interestinglyenough,

thisparalleledthedevelopmentsintheSmalltalkworldmany

yearsearlierwhenParcPlacebroughttheworld'sfirst,truly

portable,multiplatformGUIenvironmenttomarketinaproduct

calledVisualWorks(manyoftheex-ParcPlaceengineers

responsiblefortheportable,emulatedGUIlibraryin

VisualWorksendedupworkingatSun).

WhileSwingsolvedtheLCDproblembyprovidingarichsetof

widgets,theemulationoftheplatformwidgetsleftmuchtobe

desired.SwingapplicationsendedupfeelinglikeSwing

applications,nottheplatformnativeapplicationstheywere

meanttoreplace.Swingapplicationsalsosufferedfrom

performanceproblemsnotpresentintheirnativecounterparts.

WhileAWTwasabletorunontheJava2Platform,MicroEdition

(J2ME)devices,Swingcouldnotbecauseofthelargeruntime

Javavirtualmachine(JVM)footprintanditsrelianceonfast

nativegraphicstodraweveryemulatedcontrol.OTIwasgiven

thetaskwithinIBMoftoolingforJ2ME,anddecidedthatAWT

wasnotagoodenoughtoolkit.Itprovidedonlyabasicsetof

controls,andbecauseitsarchitecturenecessitatedusingthe

JavaBeanscomponentmodel,whichallowsnullconstruction,it

hadatwo-tieredobjectlayerthatusedvaluableJVM

memorysomethingimportanttomanagewiselyonsmall

devices.

UncomfortablewiththephilosophybehindSwingandemulated

widgetlibrariesingeneral,andarmedwithextensiveknowledge

abouthowtocorrectlybuildnative,portable,multiplatform

widgetlibraries,OTIsetouttocorrectthefaultsofbothAWT

andSwingandtoproducetheGUIlibrarythatAWTshouldhave

been.TheresultwastheStandardWidgetToolkit.OTIusedthe

samedeveloperswhocreatedCWforSmalltalktocreateSWT

forJava.



SWTwasdesignedtohaveassmallaJVMfootprintaspossible.

TheCWhadtwolayers,includinganOSlayer;however,for

SWT,itwasfeltthatasinglelayerwasbetter,whereeach

platform'simplementationwouldbeasetofcompletely

optimizedJavaclassesthatwentstraighttonativeassoonas

possible.ThepublicAPIwasthesame,butitwasnotdirected

throughanintermediatelayer.

OTIusedSWTtobuildVisualAgeMicroEdition(VAME),their

firstIDEwritteninJava.WhenIBMdecidedtobuildacommon

toolsplatform(Eclipse)onwhichtheycouldre-basetheir

successfulexistingproducts,theyinitiallybuiltitusingSwing.It

wasanearlyreleaseofSwinginJava1.2,andIBMwasgreatly

disappointedwithitsperformanceandlook-and-feel.There

werememoryleaksinSwinginadditiontootherdefects,which

ledtoitseventualabandonment.

OneofthereasonsSWTwaschosenwasbecauseIBM'stooling

effortwasintendedtocompetehead-to-headwithMicrosoft,

anditwasfeltthatSWTwouldgivearichenoughUI

experience.Itwasahugeriskatthetime;SWThadnotbeen

portedtomanyplatforms,andalsobyadoptingSWTtherewas

thepotentialthatcustomersmightsay:"IfSwingwasn'tgood

enoughforyourtoolkit,whyshouldweuseit?"Additionally,

anyonewritingplug-inswouldhavetouseSWTinsteadof

Swingthefearwasthattherewouldbeanaturalantagonism

towardlearningthisnewapplicationprogramminginterface

(API).TherewasalsothepossibilitythatSWTversusSwing

wouldfragmenttheJavacommunity.Allthesefearscametrue.

However,SWThasfoundalotoffavorwithpeoplewhoarenow

usingittoprogramapplicationswiththeEclipseRichClient

Platform(RCP)becausetheylikeitshigherspeedandplatform

integration.Arguably,Sundidtakeitseyeofftheballwiththe

1.2and1.3Swingreleases.WithJDK1.4,Sun'sSwing

performanceanditslook-and-feelclassesaremuchimproved,

sothatdeveloperswhouseitnowhaveagreatlyimproved

toolkit.



WithoutSWTthreateningtobecomethenewstandard,it's

difficulttoknowwhetherSunwouldhavedonethisworktotry

andcatchup,sohavingthetwotoolkitsisactuallygoodfor

usersofboth.Inthepast,interoperabilitybetweenthetwo

toolkitswaspoor,althoughthishasimproveddramaticallyin

Eclipse3.0.

SWTisthefoundationonwhichtheentireEclipseUIisbased.It

isfast,native,andmultiplatform,butitdoesnotsuffertheLCD

problempresentinAWTorthelook-and-feelproblempresentin

Swing.SWTdoesthisbytakingabest-of-both-worlds

approach:Itusesnativewidgetswheneverpossibleona

platformandsupplementsthemwithemulatedwidgetson

platformswheretheydon'texist;agoodexampleofthisisthe

treewidgetthatexistsinnativeformunderWindows,butis

emulatedunderLinux.Theresultisarich,portableAPIfor

buildingGUIapplicationsthatadhereverycloselythelook-andfeelofeachplatformtheysupport.



Note

Whileprovidingaconsistent,high-level,publicAPI,

underthecoversSWTisverydifferentfromone

platformtothenext.SWThasaunique

implementationforeachplatformandlow-levelSWT

APIsmaponetoonewiththeirplatform

counterparts.Foradetaileddiscussionabouthow

SWTinterfacestothenativeplatform,see

www.eclipse.org/articles/Article-SWT-Design-1/SWTDesign-1.html.



4.2.SWTWidgets

SWTprovidesarichsetofwidgetsthatcanbeusedtocreate

eitherstand-aloneJavaapplicationsorEclipseplug-ins.Before

goingintodetailabouteachofthewidgetsyouarelikelytouse,

itisinstructivetoexploreasimplestandaloneSWTexample.



4.2.1.Simplestand-aloneexample

Let'sstartbyrevisitingthesimpleJavaprojectandHelloWorld

applicationcreatedinChapter1,UsingEclipseTools.



4.2.1.1.AddingSWTtoyourproject'sclasspath

BeforeyoucanstartusingSWT,theSWTlibrariesneedtobe

addedtoyourproject'sclasspath.ToaddSWTsupport,dothe

following:

1. DownloadSWTforstand-aloneapplications.Astandalone

versionofSWTisavailableonthesamedownloadpageas

theEclipseSDK.LookforthesectiontitledSWTBinary

andSource.Donotextractthearchivefile,justsaveitto

disk.

2. SelectFile>Import...toopentheImportwizard.

3. SelectExistingProjectsintoWorkspaceandclickthe

Nextbutton.

4. ChooseSelectarchivefileandusetheBrowse...button

tolocatetheSWTstand-alonearchivethatyoujust

downloaded.



5. ClicktheFinishbuttontofinishimportingtheSWTproject

intoyourworkspace.

6. Right-clickontheprojectandselecttheProperties

commandtoopenthePropertiesdialog.

7. SelecttheJavaBuildPath>Projectstabandclickthe

Addbutton.

8. Selecttheorg.eclipse.swtprojectandclickOKtofinish

addingtheSWTlibrariestoyourproject'sclasspath(see

Figure4-1).



Figure4-1.JavaBuildPath>Projectsproperties.



[Viewfullsizeimage]



4.2.1.2.StandaloneSWTcode



Next,modifytheHelloWorldclasstoconvertitintoastandalone

SWTexample.Todothis,removethecontentsofthemain()

methodandreplaceitwiththefollowing:

1publicstaticvoidmain(String[]args){

2Displaydisplay=newDisplay();

3Shellshell=newShell(display);

4shell.setText("HelloWorld");

5shell.setBounds(100,100,200,50);

6shell.setLayout(newFillLayout());

7Labellabel=newLabel(shell,SWT.CENTER);

8label.setText("HelloWorld");

9Colorred=newColor(display,255,0,0);

10label.setForeground(red);

11shell.open();

12while(!shell.isDisposed()){

13if(!display.readAndDispatch())display.sleep();

14}

15red.dispose();

16display.dispose();

17}



Note

Afterenteringthenewmethodtext,selectthe

Source>OrganizeImportscommand(orpress

Ctrl+Shift+O)toaddimportsforallthereferenced

SWTclasses.



Thefollowingexamineseachlineindetail.

Line2EachSWT-basedapplicationhasoneDisplayinstancethat



representsthelinkbetweentheunderlyingplatformandSWT.

InadditiontomanagingtheSWTeventloop,italsoprovides

accesstotheplatformresourcesSWTneeds.Itwillbedisposed

inLine16.

Line3EachwindowhasaShellrepresentingthewindowframe

withwhichtheuserinteracts.Ithandlesthefamiliarmoving

andsizingbehaviorcommontoallwindowsandactsasthe

parentforanywidgetsdisplayedwithinitsbounds.

Line4ThesetText()methodisusedtosetthetitleofthe

windowframe.

Line5ThesetBounds()methodisusedtosetthesizeand

positionofthewindowframe.Intheexample,thewindow

framewillbe200pixelswide,50pixelstall,andwillbe

positioned100x100pixelsfromthetopleftcornerofthe

screen.

Line6ThesetLayout()methodsetsthelayoutmanagerforthe

windowframe.FillLayoutisasimplelayoutthatcausesthe

singlechildwidgettofilltheentireboundsofitsparent.SWT

layoutmanagerswillbediscussedindetailinSection4.3,

LayoutManagement,onpage170.

Line7Thiscreatesasimplelabelwidgetthathastheshellas

itsparentandwilldisplayitstextcenteredrelativetoitself.

Line8ThesetText()methodisusedtosetthetextofthelabel.

Line9ThiscreatesaColorinstancewiththecolorred.Notethat

youcouldusetheredsystemcolorhereaswell:

Colorred=display.getSystemColor(SWT.COLOR_RED);



Line10ThesetForeground()methodsetstheforegroundcolorof



thelabel.

Line11Uptothispoint,thewindowframehasnotbeenvisible.

Theopen()methodcausesittoappear.

Line12Thewhileloopcontinuallycheckswhetherthewindow

framehasbeenclosed.

Line13Thedisplaymanagestheeventloop.ThereadAndDispatch()

methodreadseventsfromtheplatform'seventqueueand

dispatchesthemtotheappropriatereceiver.Themethod

returnstrueaslongasthereismoreworktobedoneandfalse

whentheeventqueueisempty(thusallowingtheUIthreadto

sleepuntilthereismoreworktobedone).

Lines15and16Whentheloopdetectsthatthewindowhas

beendisposed,itisnecessarytodisposeofthecolor,display,

andanyassociatedplatformresources.Notethatsystemcolors

shouldnotbedisposed.



4.2.1.3.Runningtheexample

Normally,tolaunchaJavaapplication,youwouldusetheRun

As>JavaApplicationcommand.Doingsoatthispointwill

causean"UnsatisfiedLinkError"tobethrown,indicatingthat

theSWTnativelibrarycannotbefound.Toavoidthatproblem,

usetheRunAs>SWTApplicationcommandinstead.This

willcreateanSWTlaunchconfiguration(seeFigure4-2)that

canbeselectedintheRundialog.



Figure4-2.TheRundialog.



[Viewfullsizeimage]



Clickthedialog'sRunbuttontolaunchtheJavaapplication(see

Figure4-3).



Figure4-3.RunningthestandaloneSWT

application.



4.2.2.Widgetlifecycle

OneofSWT'sgoalsistobesmallandlean.Toachievethis,a

basicdesigndecisionwasmadethatasmuchwidgetstateas

possiblewouldbestoredintheplatformwidgetratherthanin



theSWTwidget.ThisisinmarkedcontrasttoSwing,which

maintainstheentirewidgetstatewithinthewidget.Bynot

duplicatingtheinformationmaintainedattheplatformlevel,

SWTwidgetsareverysmallwithmodestmemoryrequirements.

Onetrade-offtothisapproachisthatSWTwidgetscannot

properlyexistbythemselves.WhenanSWTwidgetiscreated,

itsunderlyingplatformcounterpartisimmediatelycreated.

Almostallrequestsforwidgetstateinformationgotothe

platformwidget.

Mostplatformsrequirethatwidgetsbecreatedwithinthe

contextofaspecificparent,soSWTrequiresthataparent

widgetbesuppliedasoneofitsconstructorarguments.Another

requirementofmanyplatformsisthatcertainstylesettings

mustbesuppliedatcreationtime(forexample,buttonscanbe

checkboxes,radiobuttons,orsimplebuttonsandtextfieldscan

besingle-ormulti-line).

StylebitsarerepresentedbyintconstantsdefinedintheSWT

class.StylesarethenOR'edtogetherandpassedasanother

constructorargumenttocreatetheinitialstyleofawidget.

Notethatallstylesarenotsupportedonallplatforms,soin

manycases,therequestedstylesaretreatedassuggestions

thatmayormaynothaveanyeffectonaparticularplatform.

AnotherplatformrequirementimposedonSWTisthat

resourcesfortheplatformshouldbeexplicitlydisposedwhen

theyarenolongerneeded.Thisappliestothewidgets

themselvesandanyresources(e.g.,graphics,fonts,andcolors)

theyhaveused.Thebasicruleis:ifyoucreateawidget,you

mustdestroythewidgetusingitsdispose()method.Ifyouuse

anysystemresources,suchassystemcolors,youshouldnot

releasethem.

Fortunately,awidgetthatisachildofanotherwidgetis

automaticallydestroyedwhenitsparentisdestroyed.This

meansthatifyouproperlydisposeofashell,youdonotneed



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

Chapter 4. The Standard Widget Toolkit

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

×