Sei sulla pagina 1di 13

Q&As | Case Studies | Blogs | White Papers | Webinars | Videos | Podcasts | Books | Events

| Magazines

| Why Subscribe?

Search

FINANCIALS

GRC

HR

SCM

CRM

BI

HANA

CLOUD

ADMIN/DEV

ROADMAP

TRENDINGTOPICS

Article

ABAP Objects in Action: Screen Programming with the


Control Framework
byHorstKellerandGisbertLoff|SAPinsider

June1,2000

byHorstKellerandGisbertLoff,SAPSAPinsider2000(Volume1),June(Issue1)

ThisarticledemonstrateshowtousecontrolswithABAPObjectstoprogram
singlescreenuserinterfaces.Italsotakesyoustepbystepthroughthe
developmentprocessandprovidessamplecodethatservesasastartingpoint
forcreatingmoreinvitinguserinterfaces.
IfyouhaveattendedarecenttrainingclassorSAPdemonstrationwhereSAP's
"flightmodel"wasusedasadatabase,youshouldrecognizetheabbreviationsAA,
AZ,andsoon,shownontheflightinformationscreeninFigure1.Butcomparedto
classicaltrainingexamples,thescreeninFigure1ismuchfancier.Theupperleft
portionshowsanairplanegraphicthathasnofunctionalityitisforvisualpurposes
only.Onthelowerleftisatreestructure,fromwhichuserscanselectcarriersorflight
connectionsfromSAP'sflightmodel.ThethirdpanedisplaystheWebsiteofthe
selectedcarrierorthedetaillistsforflightconnections.
Thisisjustoneexampleofthekindsofeasytouse,easytonavigateinterfaces
thatyoucanprovideuserswhenyoucombinethestrengthsofGUIcontroltechnology
withABAPObjects.
Inthisarticle,weshowyouhowtousecontrolswithABAPObjectstoprogram
singlescreenuserinterfaces.Afterprovidinganoverviewofthecontrolframework,
wewilltakeyoustepbystepthroughthedevelopmentprocessandprovidesome
samplecodewhichwillruninR/3Release4.6thatyoucanuseasastartingpoint
forcreatingmoreinvitinguserinterfacesinyourownapplications.

Figure1UserInterfaceoftheFlightModelProgram

ControlTechnologyOverview

TheR/3systemcommunicateswiththeuserviascreensonthefrontend.Inclassical
ABAPprogramming,screensmaycontaininput/outputfields,checkboxes,radio
buttons,andpushbuttonstointeractwiththeuser.
AlluseractionsthatraisetheruntimeeventPAI(ProcessAfterInput)andthe
respectiveprocessingontheapplicationserverareconnectedtoafunctioncodethat
istransportedtotheapplicationserver.

ControlsinGeneral
ControlsareindependentsoftwarecomponentsthatareshippedwiththeSAPGUI,
beginningwithRelease4.5.Youcanplacecontrolsonscreenstoeitherreplaceor
workalongsideclassicalcomponentsbotharesupportedinparallel.SAPcurrently
supportsActiveXcontrolsforMicrosoftWindowsplatformsandJavaBeansforthe

SAPGUIintheJavaenvironment.
Notethatcontrolsprovideagreatdealoffunctionalityandcankeepalotofdata
atthepresentationserverwithoutputtingweightontheapplicationserver(for
example,duringscrollingandeditingoftexts).Ontheotherhand,frequentdata
exchangebetweenthefrontendandbackendmayincreasethenetworkload.
Therefore,controlsareappropriatewhenmostoftheworkcanbedoneatthe
frontendandwhenexchangewiththebackenddoesnotoccurtoooften.

ControlFramework
Inordertofacilitateprogrammingwithcontrols,startingwithRelease4.6,theSAP
Basissystemprovidesacontrolframework(CFW).TheCFWencapsulatesall
availablecontrolsinglobalclassesofABAPObjects.Toworkwithcontrolsonyour
screen,simplycreateobjectsoftheseglobalclasses,calltheirmethods,andreacton
theirevents.SincetheCFWclassesarepartofaninheritancehierarchy,these
classesprovideastandardizedinterfaceformostofthecommonfunctionalityyouwill
findinthecontrols.
TheCFWdistinguishesbetweencontainercontrolsandapplicationcontrols.
Applicationcontrolsarethecomponentsyouwanttouseonthescreen.Container
controlsprovideasoftwarelayerthatstandardizesalllayoutrelatedissuesandthe
implementationofapplicationcontrols.Allapplicationcontrolsmustbelinkedtoa
containercontrolwhilethecontainercontrolislinkedtoanareaofthescreen(see
Figure2).

Figure2ContainerControlsandApplicationControlsonScreens
ContainerControls
Containercontrolsprovideareasonthescreenthatcanbeusedforapplication
controls.Themostimportantcontainercontrolsareencapsulatedinthefollowing
globalclasses:

CL_GUI_CUSTOM_CONTAINER:Whenyoucreateanobjectofthis
class,youmustlinkittoacustomcontrolonascreenviatheIMPORTING
parametercontainer_nameofitsconstructor.YoucanusetheScreenPainterto
createoneorseveralcustomcontrolswithintheareaofonescreen,andyoucan
usecustomcontrolstogetherwithclassicalscreenelements.Anyapplication
controlthatyoulinktoacustomcontainerwillappearwithinitsscreenarea.

CL_GUI_DOCKING_CONTAINER:Whenyoucreateanobjectofthis
class,youmustlinkittooneofthefouredgesofascreen.Bydoingso,you
createanewareadockedtoascreenwithoutusingtheScreenPainter.Any
applicationcontrolthatyoulinktoadockingcontainerwillappearwithinthat
screenarea.

CL_GUI_SPLITTER_CONTAINER:Whenyoucreateanobjectofthis
class,youmustlinkittoanalreadyexistingcontainercontrol.Bydoingso,you
splittheareaoftheexistingcontroleitherverticallyorhorizontallyintotwonew
areas,aswasdonetocreatethescreeninFigure1.Youcanthenlink
applicationcontrolstothenewareas.Youcanalsonestsplittercontrolstocreate
moreareas.

ApplicationControls
Aftercreatingobjectsofcontainercontrols,youcancreateobjectsofapplication
controlsthecomponentsyouwanttouseonscreen.Youmustlinkeachapplication
controltoanobjectofacontainercontrol.Youcandothisbysimplypassingthe
respectivereferencetotheparameterparentoftheapplicationcontrol'sconstructor.
Importantapplicationcontrolsandtheirrespectiveglobalclassesare:

CL_GUI_ALV_GRID:Thiscontrolallowsyoutodisplayinteractivelists.
(ALVstandsforABAPListViewer,whichreplacesclassicallistprocessing.)

CL_GUI_HTML_VIEWER:ThiscontrolallowsyoutodisplayHTML
documents.Forexample,thenewhelpvieweroftheABAPkeyword
documentationusesanHTMLcontrol.

CL_GUI_PICTURE:Thiscontrolallowsyoutodisplayanygivenpicture
onanR/3screen.Forexample,theairplaneinFigure1isdisplayedinapicture
control.SAPEasyAccessisanotherexampleofapicturecontrolasbackground.

CL_GUI_SIMPLE_TREE:Thiscontrolallowsyoutodisplayandwork
withatreestructure.Inadditiontothesimpletree,therearealsootherkindsof
treesavailable.Forexample,theObjectNavigatoroftheABAPWorkbenchuses
atreecontrol.

CL_GUI_TEXTEDIT:Thiscontrolimplementsafullfledgededitorfor
viewingandmaintainingtexts.Forexample,theABAPEditorusesatextedit
control.

ControlMethods
Youusethemethodsdefinedinthecontrol'sclassestoworkwiththecontrols
displayedonthescreen.Ingeneral,youworkwiththemethodsoftheapplication
controls.Youwouldusethese,forexample,tofilltextfromaninternaltableintothe
texteditorofthetexteditcontrol.Butsometimesyouwillalsocallmethodsofthe
CFW.Inordertominimizethenetworkloadbetweenbackendandfrontend,method
callsarebufferedinanautomationqueuebeforebeingsenttothefrontendat
definedsynchronizationpoints,suchasattheendofPBO(ProcessBeforeOutput)
processing.Toforceasynchronizationpointinyourprogram,youcancallthestatic
methodcl_gui_cfw=>flush.

ControlEventsandEventHandling
Useractionsoncontrolscantriggerevents.However,theeventsofcontrolsarenot
classicalscreenevents,whichtriggerthePAIprocessingattheapplicationserverand
sendafunctioncode.Instead,theyaredeclaredasABAPObjectseventsintheir
globalwrapperclasses.Forperformancereasons,auseractiononcontrolsisnot
automaticallypassedbacktotheapplicationserver.Ifyouwantaneventtobe
passedbacktotheapplicationserver,youmustregisteritinyourprogramusingthe
specialmethodset_registered_events,whichisavailableinallapplicationcontrols.
Youcanspecifytwokindsofeventhandling:

SystemEvents(default):Theeventispassedtotheapplicationserver,
butdoesnottriggerthePAIevent(seeFigure3).Inordertoreactontheevent,
youmustregisteraneventhandlermethodinyourABAPprogramwiththeSET
HANDLERstatement.Thismethodisthenexecutedontheapplicationserver.
Prosandcons:Thebenefitsofusingthisdefaulttechniqueisthattheevent
handlermethodisexecutedautomatically.Therealsoarenoconflictswiththe
classicalautomaticinputchecksassociatedwiththescreen.Thedisadvantageis
thatthecontentsoftheclassicalscreenfieldsthatmightexistalongsidecontrols
arenotautomaticallytransportedtotheprogram.
TIP:Ifyouworkwithclassicalscreenfieldsandyoureallyneedtotransporttheircontentsduring
controleventhandling,youcancallthestaticmethodcl_gui_cfw=>set_new_ok_codetosetafunction
codeandtriggerthePAIevent,includingafieldtransport.AfterPAIhasbeenprocessed,thePBOevent
ofthenextscreenistriggered(seeFigure3).

Figure3HandlingofSystemEvents

ApplicationEvents:Withthissecondtypeofeventhandling,theeventis
passedtotheapplicationserverandtriggersthePAI(seeFigure4).Ifyouwant
tohandletheevent,youmustincludeamethodcallforcl_gui_cfw=>dispatchin
anappropriatePAIdialogmodule.Thedispatchmethodcallsalleventhandler
methodsthataredefinedandregisteredwiththeSETHANDLERstatementfor
thatevent.Aftertheeventhandlerhasbeenprocessed,controlreturnstothePAI
moduleandPAIprocessingcontinues.
Prosandcons:Theadvantageofusingthismethodisthatyoucanspecifythe
pointatwhichtheeventishandled.Thecontentsofthescreenfieldsarealso
transportedtotheapplicationserverbeforehand.Thedisadvantageisthatthis
kindofeventhandlingcanleadtoconflictswiththeautomaticinputcheckson
thescreen,whichcancauseeventstobelost.
Whytwotypesofeventhandling?Youhavetheseoptionsbecausecontrolsmay
bedisplayedonclassicalABAPscreens,andtheremaybeclassicalscreen
elementsalongsidecontrols.Theflexibilityofthetwotypesofeventregistration

andthemethodsoftheCFW,mentionedabove,allowyoutosteerthesequence
ofdatatransportsbetweenfrontendandbackend.Ifyoudonotuseanyclassical
screencomponentsatall,youcansimplyworkwithsystemevents(thedefault
mode).

Figure4HandlingofApplicationEvents

IntroductiontotheDemonstrationProgram
Ourdemonstrationprogramisdesignedtobeassimpleaspossible.Itismeantto
demonstratethebasicconceptsofprogrammingwithGUIcontrols.Becauseofthis,
weomittedallsuperfluouscode,andwedidnotexploitallthepossibilitiesthat
controltechnologyprovides.Withtheinformationweprovideinthisarticle,youcan
goontomodifytheprogramtolearnmore.Youcanfindthecodeinourexampleat
DEMO_ABAP_OBJECTS_SPLIT_SCREENinR/3Release4.6Corhigher.
ProgramStructure
Figure5showstheprocessingblocksofthedemonstrationprogram.Theprogram
containstwolocalclasses,screen_initandscreen_handler,whichareusedtocreate
andfillthecontrolsandtoreactontheuser'sinput.Sincecontrolsaredisplayedon
classicalABAPscreens,weneedasmallclassicalframeworktocallacarrierscreen
forourcontrols.WeusetheeventblockLOADOFPROGRAMandtwodialog
modulesforthatpurpose.
Listing1showsthecodingstructureoftheprogram.Forourdemonstration
program,wehavechosentheprogramtype1(executable).Notethatwecouldhave
takenoneoftheotherprogramtypesthatsupportscreens,namelyamodulepoolor
afunctionpool.Choosinganexecutablejustsimplifiestheprogramexecution,
becauseyoucanstarttheprogramdirectlyfromtheABAPEditor.
Theprogramdoesnotcontainanyglobaldatadeclarations,anditdoesnotmakeuse
oftheclassicalreportingeventssuchasSTARTOFSELECTION.Itissimplya
containerforthethreeprocessingblocksoftheclassicalscreenframework,shownin
Figure5,andourtwolocalclasses.

Figure5StructureoftheDemonstrationProgram
PROGRAMdemo_abap_objects_split_screen.
*Classes***************************************************
CLASSscreen_initDEFINITIONCREATEPRIVATE.
...
ENDCLASS.
CLASSscreen_handlerDEFINITION.
...
ENDCLASS.
CLASSscreen_initIMPLEMENTATION.
...
ENDCLASS.
CLASSscreen_handlerIMPLEMENTATION.
...
ENDCLASS.
*Classicalprocessingblocks********************************
LOADOFPROGRAM.
...
MODULEstatus_0100OUTPUT.
...
ENDMODULE.

MODULEcancelINPUT.
...
ENDMODULE.

Listing1LayoutoftheDemonstrationProgram
TheProgramatRuntime
Figure6showswhichobjectstheprogramusestocreatethescreendisplayof
thedemonstrationprogram,alongwiththereferencesbetweentheseobjects.
Duringscreendisplay,thereisnoinstanceofthelocalclassscreen_init
becausethereisnoglobalreferencevariableintheprogramthatcanpointto
suchaninstance.Anobjectofscreen_initwillbecreatedtemporarilyduringeach
PBOprocessingofthescreen,whereitisusedasafactoryobjecttocreatethe
controlobjectsfromtheglobalclassescl_gui_splitter_container,cl_gui_picture,
andcl_gui_simple_tree.AftereachPBOprocessing,theobjectofscreen_init
willbedeletedbythegarbagecollector.Theobjectsoftheglobalclassesare
keptalivebypointersfromtheCFWbecausetheyareboundtoscreenareas.An
instanceofscreen_handlerisregisteredasaneventhandlerforeventsofobject
cl_gui_simple_tree.Thisinstanceitselfholdsreferencestoobjectsoftheglobal
classescl_gui_html_viewerandcl_gui_alv_grid.Theinstancesoftheglobal
classesarelinkedtocontrolsonthescreenviatheCFWlayer.Thetwoobjects
ofcl_gui_splitter_containersplitthescreeninthethreeareasshowninFigure1.
Theobjectsoftheapplicationcontrolsarelinkedtotheseareas.Theobjectsof
cl_gui_html_viewerandcl_gui_alv_gridarebothlinkedtothesamearea.

Figure6RuntimeObjectsoftheDemonstrationProgram

DemonstrationPrograminDetail

Thefollowingsectionsexplainthedefinitionsandtheprocessingblocksofthe
demonstrationprogramindetail.(Again,thecodeshownhereisavailableat
DEMO_ABAP_OBJECTS_SPLIT_SCREENinRelease4.6Corhigher.)
ClassicalScreenFramework
Listing2showsthecompletecodingofthethreeclassicalprocessingblocks
listedinFigure5.TheABAPruntimeenvironmentraisestheeventLOADOF
PROGRAMatthemomentwhentheprogramisstarted.Therespective
processingblockdoesnothingbutcallScreen100.Screen100iscreatedwith
theScreenPainter.Initsscreenflowlogic,thetwodialogmodulesstatus_0100
andcancelarecalledduringPBOandPAIrespectively,thelatterwiththe
additionATEXITCOMMAND.WedidnotusethegraphicalScreenPainterfor
ourexamplebecausewehavenoclassicalelementsonourscreen,andwewill
useanimplicitmethodtocreateacustomcontrol.ThePBOmodulesetsaGUI
status.Withinthatstatus,thethreefunctioncodesBACK,EXIT,andCANCEL
aredefinedwithfunctiontypeE(ExitCommand)andareactivatedinthesymbol
bar.Therefore,thePAImoduleiscalledonlywhentheuserwantstoleavethe
program.ThemostimportantactionduringPBOiscallingthestaticmethod
init_screenofclassscreen_handler.Allactualscreenhandlingisencapsulatedin
thetwolocalclasses.

LOADOFPROGRAM.
CALLSCREEN100.

MODULEstatus_0100OUTPUT.
SETPFSTATUS'SCREEN_100'.
SETTITLEBAR'TIT_100'.
CALLMETHODscreen_init=>init_screen.
ENDMODULE.
MODULEcancelINPUT.
LEAVEPROGRAM.
ENDMODULE.

Listing2ClassicalProcessingBlocksoftheDemonstration
Program
LocalClassDefinitions
Listing3showsthedeclarationpartsofthetwolocalclassesoftheprogram:
screen_initandscreen_handler.Ineachofthedeclarationparts,twovisibility
sectionsaredefinedbyusingthestatementsPUBLICSECTIONandPRIVATE
SECTION.Onlythoseclasscomponentsthatmustbeusedfromtheoutside
clientaredeclaredinthepublicsections.Allothercomponentsareencapsulated

intheprivatesections.Allattributesarereferencevariablesthatrefertoglobal
classesoftheCFW.Eachlocalclasshasaninstanceconstructorandprivate
methodsthatareusedtofillthecontrolswithdata.
Inadditiontothesegeneralfeatures,ourtwolocalclassesalsohavetheir
ownparticularfeatures:
Classscreen_inithasapublicstaticmethod,init_screen,thatcanbecalled
withoutcreatinganobjectofthatclass.
Classscreen_handlerhasaneventhandlermethodhandle_node_
double_clickthatcanhandleeventsoftheglobalclasscl_gui_simple_tree.

NotetheadditionCREATEPRIVATEinthedefinitionofscreen_initin
Listing3.Objectsofclassscreen_initcanbecreatedonlywithinclass
screen_inititself.

CLASSscreen_initDEFINITIONCREATEPRIVATE.
PUBLICSECTION.
CLASSMETHODSinit_screen.
METHODSconstructor.
PRIVATESECTION.
DATA:splitter_hTYPEREFTOcl_gui_splitter_container,
splitter_vTYPEREFTOcl_gui_splitter_container,
pictureTYPEREFTOcl_gui_picture,
treeTYPEREFTOcl_gui_simple_tree.
METHODS:fill_tree,fill_picture.
ENDCLASS.

CLASSscreen_handlerDEFINITION.PUBLICSECTION.
METHODS:constructorIMPORTINGcontainer
TYPEREFTOcl_gui_container,
handle_node_double_click
FOREVENTnode_double_click
OFcl_gui_simple_tree
IMPORTINGnode_key.
PRIVATESECTION.
DATA:html_viewerTYPEREFTOcl_gui_html_viewer,
list_viewerTYPEREFTOcl_gui_alv_grid.
METHODS:fill_htmlIMPORTINGcarridTYPEspflicarrid,
fill_listIMPORTINGcarridTYPEspflicarrid
connidTYPEspfliconnid.
ENDCLASS.

Listing3DeclarationPartsoftheTwoLocalClasses
StaticMethodinit_screen
Listing4showsthestaticmethodinit_screenofclassscreen_init.Thesingle
purposeofmethodinit_screenistocreateatemporaryobjectofclass
screen_init.Thisisdonebyusingalocalreferencevariable,screen.Duringthe
CREATEOBJECTstatement,theinstanceconstructorofscreen_initis
executed.Notethatafterleavingmethodinit_screen,thereferencevariable
screenisdeleted.Theobjectisnotreferencedanymoreandwillbedeletedby
thenextturnofthegarbagecollector.

METHODinit_screen.
DATAscreenTYPEREFTOscreen_init.
CREATEOBJECTscreen.
ENDMETHOD.

Listing4TheStaticMethodinit_screenofClassscreen_init
InstanceConstructorofscreen_init
Listing5showstheinstanceconstructorofclassscreen_init.Theinstance
constructorisusedtocreateallthecontainercontrolsonScreen100andtwoof
theapplicationcontrols(pictureandtree).Furthermore,itcreatesanevent
handlerforeventsofthetreecontrol.Mostofthedataobjectsthatareneeded
forthispurposearedeclaredlocallywithintheconstructor.Thereference
variablesoftypecl_gui_containercancontainreferencesthatpointtoany
containercontrolatthescreen.

METHODconstructor.

DATA:eventsTYPEcntl_simple_events,

eventLIKELINEOFevents,
event_handlerTYPEREFTOscreen_handler,
container_leftTYPEREFTOcl_gui_container,
container_rightTYPEREFTOcl_gui_container,
container_topTYPEREFTOcl_gui_container,
container_bottomTYPEREFTOcl_gui_container.

CREATEOBJECTsplitter_h

EXPORTING

parent=cl_gui_container=>screen0

rows=1

columns=2.

CALLMETHODsplitter_h>set_border

EXPORTINGborder=cl_gui_cfw=>false.

CALLMETHODsplitter_h>set_column_mode

CALLMETHODsplitter_h>set_column_width

EXPORTINGid=1

width=110.

container_left=splitter_h>get_container(row=1column=1).

container_right=splitter_h>get_container(row=1column=2).

CREATEOBJECTsplitter_v

EXPORTING

parent=container_left

rows=2

columns=1.

CALLMETHODsplitter_v>set_border

CALLMETHODsplitter_v>set_row_mode

CALLMETHODsplitter_v>set_row_height

EXPORTINGid=1

height=160.

container_top=splitter_v>get_container(row=1column=1).

container_bottom=splitter_v>get_container(row=2column=1).

CREATEOBJECTpicture

CREATEOBJECTtree

EXPORTINGmode=splitter_h>mode_absolute.

EXPORTINGborder=cl_gui_cfw=>false.
EXPORTINGmode=splitter_v>mode_absolute.

EXPORTINGparent=container_top.
EXPORTINGparent=container_bottom

node_selection_mode=

cl_gui_simple_tree=>node_sel_mode_single.

CREATEOBJECTevent_handler

eventeventid=cl_gui_simple_tree=>eventid_node_double_click.

eventappl_event=''.

APPENDeventTOevents.

CALLMETHODtree>set_registered_events

SETHANDLERevent_handler>handle_node_double_clickFORtree.

CALLMETHOD:me>fill_picture,

EXPORTINGcontainer=container_right.

EXPORTINGevents=events.

me>fill_tree.
ENDMETHOD.

Listing5TheInstanceConstructorofClassscreen_init
CreatingtheContainerControls
ThecodeinListing5demonstratestheprocessinvolvedincreatingthecontainer
controlsinthedemonstrationprogram:
1. Createthefirstsplittercontainer(CREATEOBJECTsplitter_h).The
constructorcreatesanobjectoftheglobalclasscl_gui_splitter_
containerusingthereferencevariablesplitter_h.IntheCREATE
statement,actualparametersarepassedtotheIMPORTING
parametersoftheglobalclass'sconstructor.
2. CreateaCustomControlatScreen100(parent=cl_gui_container
=>screen0).Bypassingthestaticattributescreen0ofclasscl_gui_
containertotheparameterparent,weusetheentireareaofScreen100
asacustomcontrolimplicitly.(Thisiswhywedidn'thavetousethe
graphicalScreenPainterforScreen100tocreateacustomcontrol.)
Alternatively,wecouldcreateacustomcontrolonScreen100withthe
graphicalScreenPainterandpassitsnameinsteadofscreen0.Then,
onlythisareawouldbeusedfordisplayingthecontrols.
TIP:Whenyouwritemorecomplexprogramsthatworkwithmorethanonescreen,you
mustcreatecustomcontrolswiththegraphicalScreenPainterinordertodistinguish
betweenthescreens.

3. Splitthescreenintotwocolumns(columns=2).Wefillthe
remainingIMPORTINGparameterswithappropriatevaluestosplit
Screen100intotwocolumns.Foreachcolumn,anewcontainercontrol
iscreated.Referencestoeachnewcontainerarestoredinasystem
tableoftheCFW.YoucannotaccessthistablefromtheABAP
program.Nevertheless,thetablelinespointtocontainercontrolobjects
oftheprogramthatarecurrentlylinkedtoascreenandpreventthese
objectsfrombeingdeletedbythegarbagecollector,evenifthe
containercontrolobjectsarenotreferencedintheprogramitself(see
Figure6).
TIP:Toremoveacontrolobjectfromtheprogram,youmustuseitsmethodfreebefore
initializingallrespectivereferencevariables.Thismethoddeletestherespectiveentry
fromtheCFWsystemtable.

4. Getreferencesofthetwocolumnsintocontainer_leftand
container_right.Afterwesetsomeattributesofthecolumnsbycalling
methodsofsplitter_h,wereadthereferencestoourcontainersfromthe
CFWintothelocalreferencevariablescontainer_leftandcontainer_right
byfunctionalcallsofmethodget_container.
5. Createtworowsintheleftcolumn(CREATEOBJECTsplitter_v).We
followthebasicprinciplesofsteps14inasimilarproceduretosplitthe
leftcolumnintotworows.Here,wepassthereferenceincontainer_left
totheconstructorofcl_gui_splitter_containerandgetreferencesofthe
twonewcontainerobjectsintothelocalreferencevariablescontainer_
topandcontainer_bottom.

CreatingtheApplicationControlsBygoingthroughthestepslistedabove,we
havecreatedallthecontainercontrolsthatweneed.Nowwecangoonto
createourapplicationcontrols.TheprocessisshowninthecodeinListing5,
andinvolvesthesesteps:
1. Createapplicationcontrolsfortheleftcolumn(CREATEOBJECT
pictureandCREATEOBJECTtree).Withtheinstanceconstructorof
classscreen_init,wecreatethetwoapplicationcontrolsforthe
containersintheleftcolumn.Intheuppercontainer,wecreateanobject
ofcl_gui_picture.Inthelowercontainer,wecreateanobjectof
cl_gui_simple_tree.Welinktheobjectstotherespectivecontainer
controlsbypassingthereferencesincontainer_topandcontainer_
bottomtotheirconstructor'sIMPORTINGparameterparent.
2. Createaneventhandler(CREATEOBJECTevent_handler).Sincewe
wantourprogramtoreactonuseractionsinthetreecontrol,wemust
provideandregisteraneventhandler:
1. First,wecreateanobjectofourlocalclassscreen_handler.
2. TheconstructorofthisclassdemandsanIMPORTINGparameterof
typecl_gui_container.Wepassthereferencetotherightcolumn's
containercontrol.
3. Inordertoregisterourobjectofclassscreen_handlerasanevent
handlerforthetreecontrol,wemustcallthespecialmethod
set_registered_eventsaswellasthesimpleSETHANDLER
statement(see"ControlEventsandEventHandling"above).
4. Theparametersarepassedviaaninternaltableoftypecntl_
simple_events,whichisdefinedintheABAPDictionary.
5. Bymovingablankcharacter''(defaultvalue)andnotan'X'tothe
componentappl_event,wedefinethattheeventishandledasa
systemevent(default)andnotasanapplicationevent.

3. Sendinitialdatatotheapplicationcontrols(callmethod:me>fillpicture,
me>filltree).Finally,theconstructorcallsthemethodsfill_pictureand
fill_treetoinitializethecontentsofourapplicationcontrolsonthe
screen.
Methodfill_picture
Listing6showstheinstancemethodfill_pictureofclassscreen_init.The
methodfill_pictureimportsapictureinGIFformatfromanindxtypedatabase
tableabtreeintoalocalinternaltablepict_tab.Thefunctionmodule
dp_create_urlcreatesaURLforthatinternaltableandpassesittothelocal
variableurl.BypassingthatURLtomethodload_picture_from_urlofourpicture
controlobject,wesendthepicturetothepicturecontrolatthescreen.The
methodset_display_modeallowsustosettheattributesofthepicturedisplayed
inthecontrol.
Insteadofworkingwithaninternaltable,youcanalsousealocalpicturefile
fromyourpresentationserverandpassitsnamedirectlytotheparameterurlof
methodload_picture_from_url.Ourprogramhastheadvantageofworkingforall
users.

METHODfill_picture.

TYPESpict_line(256)TYPEc.

DATApict_tabTYPETABLEOFpict_line.

DATAurl(255)TYPEc.

IMPORTpict_tab=pict_tabFROMDATABASEabtree(pi)ID'FLIGHTS'.

CALLFUNCTION'DP_CREATE_URL'

EXPORTING

type='IMAGE'

subtype='GIF'

TABLES

data=pict_tab

CHANGING

CALLMETHODpicture>load_picture_from_urlEXPORTINGurl=url.

url=url.

CALLMETHODpicture>set_display_mode

EXPORTINGdisplay_mode=picture>display_mode_fit_center.
ENDMETHOD.

Listing6TheInstanceMethodfill_pictureofClassscreen_init
TIP:Howcanyousavepicturesinanindxtypedatabasetable?Listing7
showsalittlehelperroutinethatfulfillsthatpurpose.Provideyourfavorite
pictureinafolder(forexample,C:\TEMP\ofyourpresentationserver)and
simplyrunthisprogram.Theprogramloadsthepictureinbinaryformatintoan
internaltableandexportsittoanindxtypedatabasetable.(Westrongly
recommendthatyoucreateyourownindxtypetableinsteadofusingabtreeor
indxitself!)

REPORTpicture_save.
PARAMETERSfileTYPErlgrapfilenameDEFAULT'C:\TEMP\.GIF'.
PARAMETERSid(20)TYPEc.
DATApict_line(256)TYPEc.
DATApict_tabLIKETABLEOFpict_line.
CALLFUNCTION'WS_UPLOAD'

EXPORTING

filename=file

filetype='BIN'

TABLES

data_tab=pict_tab.

EXPORTpict_tab=pict_tabTODATABASEabtree(pi)IDid.

Listing7HelperRoutinetoSaveGIFsinaDatabaseTable
Methodfill_tree
Listing8showstheinstancemethodfill_treeofclassscreen_init.Tocreatea
treelikestructurewithinthetreecontrol,youmustcallmethodadd_nodesand
passaninternaltableofspecialstructureandcontentstothatmethod.The
additionTYPETABLEOFinthedeclarationofnode_tableinListing8shows
thatthelinetypeofthatinternaltableisabdemonode,definedintheABAP
Dictionary.Youcancreatesuchtypesbycopyingtheglobaltemplatestructure
mtreesnode.
Theinternaltablecontainsonelineforeachnodeofthetree.Eachnodemust
haveauniquekeynode_key.Thecolumnsrelatkeyandrelatshipdescribethe
relationsbetweenthenodes.Youcanalsoadddescriptiontexts,changethe
standardicons,andsoon.Inourexample,wecreateanodetablefromthe
contentsofdatabasetablespfli.Thedatabasetablespfliisthewellknowntable
offlightconnectionsfromSAP'straininganddemonstrationflightmodel.
Weselectalldatafromspfliintothesortedinternaltablespfli_taband
processthistableinaloop.There,wefilltheinternaltablenode_tablewithlines
thatrepresentatreestructureoftwohierarchylevels.Theattributesofthe
nodesaresetbyassigningflagstosomecolumnsofnode_table.Notethatwe
replacethestandardfoldericonwithanairplaneiconforthesubnodesby
assigningtheinternalcode"@AV@"totheimagecolumns.

METHODfill_tree.

DATA:node_tableTYPETABLEOFabdemonode,

nodeTYPEabdemonode,
spfli_waTYPEspfli,
spfli_tabTYPESORTEDTABLEOFspfli
WITHUNIQUEKEYcarridconnid.

SELECTcarridconnid

FROMspfli

INTOCORRESPONDINGFIELDSOFTABLEspfli_tab.

nodehidden=''.

nodedisabled=''.

nodeisfolder='X'.

nodeexpander=''.

LOOPATspfli_tabINTOspfli_wa.

ATNEWcarrid.

nodenode_key=spfli_wacarrid.

CLEARnoderelatkey.

CLEARnoderelatship.

nodetext=spfli_wacarrid.

noden_image=''.

nodeexp_image=''.

APPENDnodeTOnode_table.

ENDAT.

ATNEWconnid.

CONCATENATEspfli_wacarridspfli_waconnid

noderelatkey=spfli_wacarrid.

noderelatship=cl_gui_simple_tree=>relat_last_child.

nodetext=spfli_waconnid.

noden_image='@AV@'.

nodeexp_image='@AV@'.

ENDAT.

APPENDnodeTOnode_table.

INTOnodenode_key.

ENDLOOP.
CALLMETHODtree>add_nodes

EXPORTINGtable_structure_name='ABDEMONODE'

node_table=node_table.
ENDMETHOD.

Listing8TheInstanceMethodfill_treeofClassscreen_init
TIP:TofindtheinternalcodesofallSAPicons,executethereport
SHOWICON.
InstanceConstructorofscreen_handler
Listing9showstheinstanceconstructorofclassscreen_handler.Theinstance
constructorofclassscreen_initcreatesanobjectofclassscreen_handler.This
meansthattheexecutionoftheinstanceconstructorofclassscreen_handleris
embeddedintheexecutionoftheinstanceconstructorofclassscreen_init.It
createstwoapplicationcontrolobjects,bothofwhicharelinkedtotheright

columnofourverticalsplittercontrol.Rememberthattheinstanceconstructorof
classscreen_initpassesthereferencetotherightcolumn'scontainercontroland
totheconstructor'sparametercontainerintheCREATEOBJECTstatement.
TheapplicationcontrolscandisplayeitherHTMLpagesorlists,buttheyarenot
filledduringtheconstructor'sexecutionyet.Fillingthesecontrolsdependsonthe
user'sactioninthetreecontrol.

METHODconstructor.

CREATEOBJECT:html_viewerEXPORTINGparent=container,

list_viewerEXPORTINGi_parent=container.
ENDMETHOD.

Listing9TheInstanceConstructorofClassscreen_handler
Methodhandle_node_double_click
Listing10showstheinstancemethodhandle_node_double_clickofclass
screen_handler.Thismethodisdeclaredandregisteredasaneventhandlerfor
theeventnode_double_clickofourtreecontrolobject.Therefore,eachtimea
userdoubleclicksonanodeofthetree,ittriggersthatmethod.Themethod
importstheevent'sEXPORTINGparameternode_key,whichcontainsthekeyof
theselectednode.Dependingonthekey'scontents,theeventhandlereither
callsmethodfill_htmlorfill_list.Italsosetsthevisibilityofthetwoapplication
controlsreferencedbyhtml_viewerandlist_viewer.Rememberthatbothcontrols
arelinkedtotherightcolumnofourverticalsplittercontrol.Theeventhandler
steerstheiralternativedisplayinthatcontainer.
Asstatedabove,methodcallstothefrontendarebufferedinanautomation
queue.Butsincethereisnoautomaticsynchronizationpointafterhandlinga
systemeventonthebackend,wemustforcethesystemtoprocessthe
precedingmethodcalls.Todothis,wemustcallthestaticmethod
cl_gui_cfw=>flush.NotethatwedonothaveanyregularPAIprocessinginour
programexceptwhentheuserleavesthescreen.Thecommunicationbetween
frontendandbackendishandledbytheCFW.Thefrontendtobackend
communicationistriggeredbyevents,andthebackendtofrontend
communicationistriggeredbyflushes.

METHODhandle_node_double_click.

DATA:carridTYPEspflicarrid,

connidTYPEspfliconnid.

carrid=node_key(2).

connid=node_key+2(4).

IFconnidISINITIAL.

CALLMETHOD:fill_htmlEXPORTINGcarrid=carrid,

html_viewer>set_visibleEXPORTINGvisible='X',
list_viewer>set_visibleEXPORTINGvisible=''.

ELSE.

CALLMETHOD:fill_listEXPORTINGcarrid=carrid

connid=connid,

list_viewer>set_visibleEXPORTINGvisible='X',

html_viewer>set_visibleEXPORTINGvisible=''.

ENDIF.

CALLMETHODcl_gui_cfw=>flush.

ENDMETHOD.

Listing10TheInstanceMethodhandle_node_double_clickof
Classscreen_handler
Methodfill_html
Listing11showstheinstancemethodfill_htmlofclassscreen_handler.Whena
userselectsanode,thismethodreadsthevalueofcolumnURLfromthe
databasetableSCARRaccordingtothenodeselected.TheselectedURLis
simplypassedtothemethodshow_urlofourHTMLcontrol,whichdisplaysitin
itsareaonthescreen.
BeginningwithRelease4.6C,thenewcolumnURLofthecarrierdatabase
tableSCARRwillcontaintheaddressesofthecarrier'sWebsites.Toadd,
change,orupdatetheaddresses,youcanprovideyourowndataandchangethe
programaccordingly.

METHODfill_html.

DATAurlTYPEscarrurl.

SELECTSINGLEurl

FROMscarr

INTOurl

WHEREcarrid=carrid.

CALLMETHODhtml_viewer>show_urlEXPORTINGurl=url.

ENDMETHOD.

Listing11TheInstanceMethodfill_htmlofClass
screen_handler
Methodfill_list
Listing12showstheinstancemethodfill_listofclassscreen_handler.This

methodgivesyouanimpressionofhowtoworkwiththenewSAPListViewer,
whichwillreplaceclassicalABAPlistprocessing.Aswiththetreecontrol,you
havetopreparedatainaninternaltableandpassthistabletoamethodofthe
ListViewerobject.Inourcase,wereaddetailinformationfromdatabasetable
sflightintoaninternaltableflight_tabwhentheuserhasdoubleclickedaflight
connectioninthetree.Inadditiontotheactualdata,weprepareandpass
additionalinformationsuchasthelist'stitleandsomeofitsattributestothe
method.Figure7showsthescreenafterselectingaflightconnectioninthe
tree.

METHODfill_list.

DATA:flight_tabTYPETABLEOFdemofli,

BEGINOFflight_title,

carrnameTYPEscarrcarrname,

cityfromTYPEspflicityfrom,

citytoTYPEspflicityto,

ENDOFflight_title,

list_layoutTYPElvc_s_layo.

SELECT SINGLEc~carrnamep~cityfromp~cityto

INTO

CORRESPONDINGFIELDSOFflight_title

FROM

(scarrASc

WHERE

p~carrid=carridAND

SELECT fldateseatsmaxseatsocc

INTO

CORRESPONDINGFIELDSOFTABLEflight_tab

FROM

sflight

WHERE

carrid=carridANDconnid=connid

ORDERBYfldate.

CONCATENATEflight_titlecarrname

INNERJOINspfliASpONc~carrid=p~carrid)

p~connid=connid.

connid
flight_titlecityfrom
flight_titlecityto
INTOlist_layoutgrid_title
SEPARATEDBYspace.

list_layoutsmalltitle='X'.

list_layoutcwidth_opt='X'.

list_layoutno_toolbar='X'.

CALLMETHODlist_viewer>set_table_for_first_display

EXPORTINGi_structure_name='DEMOFLI'

is_layout=list_layout

CHANGING

it_outtab=flight_tab.

ENDMETHOD.

Listing12TheInstanceMethodfill_listofClassscreen_handler

Figure7ListDisplaywithanALVControl

Conclusion

Inthisarticle,weshowedyoutheprincipalconceptsofprogrammingscreens
withthecontrolframeworkusingadetaileddemonstrationprogram.This
procedurecanbecondensedintothefollowingsteps:
1. Createcontainercontrolobjectsandlinkthemtoareasatthescreen.
2. Createapplicationcontrolobjectsandlinkthemtothecontainercontrols.
3. Providedataforthecontrolsindataobjects,which,inmostcases,are
internaltablesofspecialglobaltypes.
4. Sendthedatatothecontrolsbycallingcontrolmethods.
5. Reactonuseractionsonthecontrolsbydefiningandregisteringevent
handlermethods.
Inthisarticle,wedidnotexplainthesinglecontrolclassesortheirmethods
andeventsingreatdetail.Wesimplywantedtoprovideanoverviewforthe
ABAPObjectsprogrammerwhowantstouseglobalclassesoftheCFWand
whodefineshisorherownlocalclassestohandlethecontrolobjectsonthe

screen.
Usingthisarticleasastartingpoint,youcanlearnmoreaboutthefeaturesof
thecontrolframeworkbyreferringtothedocumentationofthecontrolclassesor
totheirdefinitionintheclassbuilderoftheABAPWorkbench.Withthat
information,youcanthencontinuetoexploretheCFWonyourown.For
example,youmightcreateclassesthatreactwhenauserclicksonapicture.Or
youcouldlookfurtherintotreecontrols,sothatwhenauserselectsanodeina
treecontrol,youcouldintroducecontextmenusforthosenodes.Userswould
thenfindthesewhentheyrightclickonaparticularnode.Finally,thereismuch
todiscoverabouttheALV,whichwecoveredonlybriefly.ALVisthebestchoice
forpresentingtabulardataonthescreen.Itreplacesclassicaltablecontrolsas
wellasclassicallists,anditprovidesacompleteenvironmentforinteractive
reporting.
IfyouwishtodesignandimproveGUIfeaturesthatbenefityourusers,the
opportunitiesarethere,andthedevelopmentprocessfortheseinterfacesismore
streamlinedthaneverbefore.Whicheverfeaturesyouchoosetotakeadvantage
of,thisarticlecanbeyourspringboardtocreatinganinterfacethatisaneffective
toolforyourendusers.

HorstKellerisinformationdeveloperintheSAPABAP&GUIGroup.He
documentstheABAPlanguagewithanemphasisonABAPObjects.Healso
developsandteachesclassesonABAPprogrammingandgivesworkshopsat
technicaleducationconferences.Youcanreachhimathorst.keller@sap.com.
GisbertLoffisproductmanagerintheSAPABAP&GUIGroup,wherehe
handlesallGUIrelatedissues.Hehasgivenvariouslecturepresentationsand
workshopsattechnicaleducationconferencesandSAPPHIREs.Youcanreach
himatgisbert.loff@sap.com.

Didyoufindthisarticlehelpful?Getaccesstothelatest
updatesandresourcesfromSAPinsiderwithafree
subscription.
GettheSAPinsidersubscriptionnow

MorefromSAPinsider
LeverageYourCurrentIT
InfrastructureinSAP
HANADeployments
Thereismorethanonewayto
deploySAPHANA.Asan
alternativetoimplementinga
fullypreconfiguredSAPHANA
appliance,SAPalsosupportsa
TailoredDatacenterIntegration
(TDI)model...

KeystoSuccessfor
BarcodeLabelingfrom
SAP
Attendthiswebinartofindout
howKerrydramaticallyreduced
labelingerrors,improved
consistencyandcutcostsby
standardizingonanEnterprise
LabelingSolutionthatleverages
SAP.Registertodayto...

askSAPSetsSightson
Analytics,BigDatain
LatestCommunityCall
DetailsontheSept.17
#askSAPAnalyticsInnovations
CommunityCallwithSAP
MentorTammyPowlas,SAP
expertsTyMillerandAngela
Harvey,andguestspeaker
JustinSearsofHortonworks....

COMMENTS
Pleaselogintopostacomment.
Nocommentshavebeensubmittedonthisarticle.Bethefirsttocomment!

ABOUT US

SAPinsiderispublishedbyWISPublishing,a
divisionofWellesleyInformationServices.
20CarematrixDrive,Dedham,MA02026USA
SalesandCustomerService:1(781)7518799
customer@wispubs.com
2015WellesleyInformationServices.Allrights
reserved.
OnlineISSN#21552444,PrintISSN#1537145X
SAPandtheSAPlogoaretrademarksorregistered
trademarksofSAPSEinGermanyandother
countries.

CONTACT US

PRESS ROOM

MEDIA KIT

FAQ

PRIVACY POLICY

SAPinsider

insiderPROFILES

SAPinsiderConferences&Seminars

insiderRESEARCH

SAPinsiderSeminarsonDemand

SAPexperts

SAPinsiderStore

SITEMAP

Potrebbero piacerti anche