Você está na página 1de 195

TheCompleteGuidetoJ2MEPolish

TheSolutionfor
ProfessionalWirelessJavaDevelopment

1
TableofContents
Preamble.............................................................................................................................9
IntroductiontoJ2MEPolish............................................................................................11
Installation......................................................................................................................11
AnExampleApplication..................................................................................................11
BuildingtheApplication..................................................................................................11
DesigningtheApplicationwithCSS...............................................................................12
DebuggingandLogging.................................................................................................14
EasyDeviceOptimizationswithPreprocessingandtheDeviceDatabase....................15
FunFunFun:TheGameEngine....................................................................................16
ExtendingJ2MEPolish..................................................................................................17
Installation........................................................................................................................18
Requirements.................................................................................................................18
InstallationofJ2MEPolish.............................................................................................18
UpdatingJ2MEPolish....................................................................................................18
IntegratingJ2MEPolishintoEclipse..............................................................................18
IntegratingJ2MEPolishintoBorland'sJBuilder.............................................................19
IntegratingJ2MEPolishintoNetBeans..........................................................................20
NetBeans3.6..........................................................................................................................20
NetBeans4.x..........................................................................................................................20
NetBeans5.x...........................................................................................................................21
SetupandConfigurationofAnt......................................................................................21
IntegratingJ2MEPolishwithanExistingProject...........................................................22
TheDeviceDatabase.......................................................................................................23
vendors.xml....................................................................................................................23
groups.xml......................................................................................................................23
devices.xml.....................................................................................................................24
apis.xml..........................................................................................................................25
ExtendingtheDevicDatabase.......................................................................................26
DeviceCapabilities.........................................................................................................26
TheBuildProcess............................................................................................................28
Introduction....................................................................................................................28
DefinitionoftheJ2MEPolishtask.................................................................................28
Example.........................................................................................................................28
The<info>Section.........................................................................................................31
The<deviceRequirements>Section..............................................................................33
The<build>Section.......................................................................................................36
AttributesofthebuildSection.................................................................................................36
ElementsofthebuildSection.................................................................................................39
<sources>..........................................................................................................................39
<midlet>and<midlets>......................................................................................................40

2
<iappli>...............................................................................................................................40
<resources>.......................................................................................................................41
The<filter>Subelement..............................................................................................................................42
The<fileset>Subelement............................................................................................................................42
The<localization>Subelement...................................................................................................................43
The<copier>Subelement............................................................................................................................43
TheantcallResourceCopier..................................................................................................................44
TherenamerResourceCopier................................................................................................................44
ThesvgconverterResourceCopier........................................................................................................45
<compiler>.........................................................................................................................45
The<compilerargs>Subelement.................................................................................................................47
<obfuscator>......................................................................................................................48
The<keep>Subelement..............................................................................................................................49
The<parameter>Subelement......................................................................................................................49
CombiningSeveralObfuscators..................................................................................................................50
SpecificObfuscatorSettings........................................................................................................................50
ProGuard................................................................................................................................................50
yGuard....................................................................................................................................................50
RetroGuard.............................................................................................................................................51
ZelixKlassMaster...................................................................................................................................51
DashOPro..............................................................................................................................................51
JODE......................................................................................................................................................52
<variables>and<variable>................................................................................................52
<debug>.............................................................................................................................54
<jad>..................................................................................................................................55
SortingandFilteringJADattributes............................................................................................................56
<manifestFilter>.................................................................................................................57
<preprocessor>..................................................................................................................58
<java>................................................................................................................................59
<packager>........................................................................................................................60
The<emulator>Section.................................................................................................61
Attributesofthe<emulator>Section......................................................................................62
The<parameter>Subelement................................................................................................63
EmulatorSettingsintheDeviceDatabaseandinthebuild.xml.............................................63
WTKEmulators..................................................................................................................63
NokiaEmulators.................................................................................................................64
SiemensEmulators............................................................................................................64
MotorolaEmulators............................................................................................................64
LaunchinganyEmulatorwiththeGenericEmulatorImplementation.................................64
AutomaticResolvingofStackTracesandExceptions............................................................65
ResourceAssembling......................................................................................................67
Concepts........................................................................................................................67
OftenUsedGroups........................................................................................................67
FineTuningtheResourceAssembling..........................................................................69
Localization.......................................................................................................................70
Concepts........................................................................................................................70
The<localization>ElementandLocalizedResourceAssembling.................................71
ManagingTranslations...................................................................................................71
TheLocaleClass....................................................................................................................71

3
DynamicTranslations..............................................................................................................72
DefiningTranslations...............................................................................................................73
SettingandUsingLocalizedVariables....................................................................................74
UsingLocalizedAttributes.......................................................................................................74
CopingwithDatesandCurrencies.................................................................................74
CommonTraps...............................................................................................................75
AdjustingtheJARname.........................................................................................................75
UsingQuotationMarksandOtherSpecialCharactersinTranslations..................................75
InvalidLocaleCalls.................................................................................................................75
LocalizingtheJ2MEPolishGUI.....................................................................................76
TheWorldofPreprocessing............................................................................................78
CheckingaSingleSymbolwith#ifdef,#ifndef,#else,#elifdef,#elifndefand#endif......78
CheckingSeveralSymbolsandVariableswith#if,#else,#elifand#endif....................79
UsingVariableFunctionsforComparingValues....................................................................81
HidingCode...................................................................................................................82
Debuggingwith#debug,#mdebugand#enddebug......................................................82
DebugLevels..........................................................................................................................83
TheDebugUtilityClass..........................................................................................................84
UsingVariableswith#=..................................................................................................84
VariableFunctions..................................................................................................................85
SettingCSSStyleswith#style.......................................................................................86
ExcludeorIncludeCompleteFileswith#condition........................................................87
DefiningTemporarySymbolsorVariableswith#defineand#undefine.........................87
InsertingCodeFragmentswith#include........................................................................88
AnalyzingthePreprocessingPhasewith#messageand#todo....................................88
HandlingSeveralValuesinVariableswith#foreach.....................................................89
UsefulSymbols..............................................................................................................90
APIsandMIDPVersion..........................................................................................................90
J2MEPolishSymbols.............................................................................................................90
UsefulVariables.............................................................................................................90
FileOperations........................................................................................................................91
TheJ2MEPolishGUI.......................................................................................................92
Overview........................................................................................................................92
ActivationoftheGUI......................................................................................................92
ConfiguringtheJ2MEPolishGUI..................................................................................93
UsingtheGUIinFullScreenMode........................................................................................93
ConfiguringCommands,LabelsandProgrammingoftheGUI..............................................95
TheJ2MEPolishGUIforProgrammers.........................................................................96
SettingStyles..........................................................................................................................97
UsingDynamicandPredefinedStyles....................................................................................98
PortingMIDP/2.0ApplicationstoMIDP/1.0Platforms............................................................99
ProgrammingSpecificItemsandScreens..............................................................................99
ProgrammingtheTabbedForm..........................................................................................99
TheJ2MEPolishGUIforDesigners............................................................................102
AQuickGlance.....................................................................................................................102

4
DesigningforSpecificDevicesorDeviceGroups................................................................103
TheHierarchyoftheresourcesFolder..........................................................................103
Groups..............................................................................................................................104
APIandJavaPlatformGroups.................................................................................................................104
BitsPerPixelGroups...................................................................................................................................104
Dynamic,StaticandPredefinedStyles.................................................................................105
StaticStyles......................................................................................................................106
PredefinedStyles.............................................................................................................106
DynamicStyles.................................................................................................................107
ExtendingStyles...................................................................................................................109
CSSSyntax...........................................................................................................................109
StructureofaCSSDeclaration.............................................................................................109
Naming.............................................................................................................................110
GroupingofAttributes.......................................................................................................110
ReferringtoOtherStyles..................................................................................................110
Comments........................................................................................................................110
CommonDesignAttributes....................................................................................................111
Structureofpolish.css......................................................................................................111
StructureofaStyleDefinition...........................................................................................111
TheCSSBoxModel:MarginsandPaddings...................................................................112
TheLayoutAttribute.........................................................................................................113
Colors...............................................................................................................................114
PredefinedColors.......................................................................................................................................114
ThecolorsSection......................................................................................................................................115
HowtoDefineColors................................................................................................................................115
AlphaBlending...........................................................................................................................................116
Fonts.................................................................................................................................116
BitmapFonts....................................................................................................................117
CreatingBitmapFonts...............................................................................................................................117
UsingBitmapFontsintheJ2MEPolishGUI............................................................................................117
UsingBitmapFontsDirectly....................................................................................................................118
Labels...............................................................................................................................118
BackgroundsandBorders................................................................................................119
BeforeandAfterAttributes...............................................................................................119
SpecificDesignAttributes.....................................................................................................120
Backgrounds....................................................................................................................120
SimpleBackground....................................................................................................................................120
RoundRectBackground............................................................................................................................120
ImageBackground.....................................................................................................................................121
CircleBackground.....................................................................................................................................122
PulsatingBackground................................................................................................................................123
PulsatingCircleBackground.....................................................................................................................123
PulsatingCirclesBackground....................................................................................................................124
OpeningBackground.................................................................................................................................124
OpeningRoundRectBackground.............................................................................................................125
RoundTabBackground.............................................................................................................................126
SmoothColorBackground....................................................................................................126
TigerStripesBackground......................................................................................................127
BallGamesBackground.......................................................................................................127
Borders.............................................................................................................................128

5
SimpleBorder............................................................................................................................................128
RoundRectBorder....................................................................................................................................129
ShadowBorder...........................................................................................................................................129
Top,Bottom,LeftandRightBorder..........................................................................................................130
CircleBorder..............................................................................................................................................130
Screens:List,FormandTextBox.....................................................................................131
PredefinedStylesforLists,FormsandTextBoxes.....................................................................................131
AdditionalAttributesforScreens...............................................................................................................131
DynamicStylesforScreens.......................................................................................................................133
List........................................................................................................................................................133
Form.....................................................................................................................................................133
TextBox................................................................................................................................................133
Commands.................................................................................................................................................133
Example.....................................................................................................................................................134
ViewTypes.......................................................................................................................136
DroppingView...........................................................................................................................................136
ShuffleView..............................................................................................................................................137
MIDP/2.0View..........................................................................................................................................137
TheStringItem:Text,HyperlinkorButton........................................................................137
TheIconItem....................................................................................................................138
TheChoiceItem................................................................................................................138
TheChoiceGroup.............................................................................................................139
TheGauge.......................................................................................................................140
TheTextField....................................................................................................................141
TextFieldCommands.................................................................................................................................142
DirectInputMode......................................................................................................................................142
TheDateField...................................................................................................................144
TheTicker........................................................................................................................145
TheMenuBar...................................................................................................................145
TheExtendedMenuBar..................................................................................................146
TheTabbedForm..............................................................................................................148
TheMIDP/2.0CompatibleGameEngine......................................................................149
HowItWorks................................................................................................................149
Limitations....................................................................................................................149
Optimizations................................................................................................................149
UsingaFullscreenGameCanvas........................................................................................150
BackbufferOptimizationfortheTiledLayer...........................................................................150
SplittinganImageintoSingleTiles.......................................................................................151
DefiningtheGridTypeofaTiledLayer..................................................................................151
UsingtheGameEngineforMIDP/2.0Devices.....................................................................151
PortingaMIDP/2.0GametoMIDP/1.0Platforms........................................................152
BuildingtheExistingApplication...........................................................................................152
Adjustingthebuild.xml.....................................................................................................152
ManagingtheResources.................................................................................................153
BuildingtheGame............................................................................................................154
PortingtheGametoMIDP/1.0..............................................................................................154
NecessarySourceCodeChanges...................................................................................154
WorkingAroundtheLimitationsoftheGameEngine......................................................154
PixelLevelCollisionDetection.................................................................................................................154

6
SpriteTransformations...............................................................................................................................154
UsingPreprocessingforDeviceSpecificAdjustments....................................................156
ExtendingJ2MEPolish..................................................................................................157
IntegratingaCustomObfuscator.................................................................................157
Preparations..........................................................................................................................157
CreatingtheObfuscatorClass..............................................................................................157
IntegratingtheObfuscatorintothebuild.xml........................................................................158
ConfiguringtheObfuscatorwithParameters........................................................................158
CreatingandUsingCustomPreprocessingDirectives.................................................159
Preparations..........................................................................................................................159
CreatingthePreprocessorClass..........................................................................................159
UsingtheregisterDirective()Method...............................................................................159
UsingtheprocessClass()Method....................................................................................160
IntegratingthePreprocessorintothebuild.xml.....................................................................160
ConfiguringthePreprocessorwithParameters....................................................................161
ExtendingtheJ2MEPolishGUI...................................................................................161
UsingCustomItems..............................................................................................................161
Initialisation.......................................................................................................................161
InteractionModes.............................................................................................................161
Traversal...........................................................................................................................161
UsingCSSforDesigningtheCustomItem.......................................................................162
RegisteringCustomCSSAttributes...........................................................................................................163
BackgroundsandBorders................................................................................................164
AddingaCustomBackground..............................................................................................164
CreatingtheClientSideBackgroundClass.....................................................................164
CreatingtheServerSideBackgroundClass...................................................................166
IntegratingtheCustomBackground.................................................................................167
AddingaCustomBorder.......................................................................................................168
CreatingtheClientSideBorderClass.............................................................................168
CreatingtheServerSideBorderClass............................................................................169
IntegratingtheCustomBorder.........................................................................................170
ContributingYourExtensions.......................................................................................171
StandaloneTools............................................................................................................172
TheBinaryDataEditor.................................................................................................172
TheFontEditor.............................................................................................................173
NonMIDPPlatforms.......................................................................................................175
DevelopingforBlackBerryDevices..............................................................................175
Preparations..........................................................................................................................175
ConvertingJARsintoCODs..................................................................................................175
SigningCODFiles.................................................................................................................175
UsingtheJ2MEPolishGUIonBlackBerryDevices.............................................................176
DevelopingNativeBlackBerryApplications..........................................................................176
Troubleshooting.....................................................................................................................176
DeactivateObfuscation....................................................................................................176
Library...............................................................................................................................176
DevelopingforPalmDevices.......................................................................................177

7
Preparations..........................................................................................................................177
ConvertingJARsintoPRCs..................................................................................................177
StartingthePalmSimulator..................................................................................................178
DevelopingDoJaApplicationswithJ2MEPolish..........................................................178
Preparations..........................................................................................................................178
J2MEPolishSetup................................................................................................................178
OptionalJAMAttributes.........................................................................................................179
DevelopingDoJaApplicationsunderLinuxandMacOSX..................................................179
DevelopingforMIDPandDoJaattheSameTime...............................................................180
CookingTipsandHowTos............................................................................................181
BuildingHowTos..........................................................................................................181
HowtoUseSeveralSourceFolders.....................................................................................181
HowtoIntegrateThirdPartyAPIs........................................................................................181
HowtoIntegrateaSourceCodeThirdPartyAPI...........................................................181
HowtoIntegrateaBinaryThirdPartyAPI......................................................................182
HowtoIntegrateaDeviceAPI........................................................................................182
HowtoUseSeveralObfuscatorsCombined........................................................................183
HowtoMinimizetheMemoryFootprint................................................................................183
polish.skipArgumentCheckandpolish.debugVerbose.....................................................183
ImageLoadStrategy........................................................................................................183
Optimizingthe"polish.css"File........................................................................................183
UsingOptimalResources................................................................................................184
UsePreprocessing...........................................................................................................184
RemoveDebugCode.......................................................................................................186
GeneralOptimizationTips................................................................................................186
HowtoSignMIDletswithJ2MEPolish.................................................................................186
GUIHowTos................................................................................................................187
HowtoUseTables................................................................................................................187
HowtoApplytheJ2MEPolishGUIforExistingApplications...............................................187
HowtoApplyDifferentDesignstoOneApplication..............................................................188
HowtoChangetheLabelsofStandardCommandsandMenuLabels...............................189
HowtoEnableorDisabletheUsageoftheGUIforaSpecificDevice.................................189
TroubleShooting..........................................................................................................190
UsingSubfoldersforResources...........................................................................................190
CompileError........................................................................................................................190
PreverifyError.......................................................................................................................190
Appendix.........................................................................................................................191
IntroductiontoAnt........................................................................................................191
HowtoUseQuotationMarksinAttributes............................................................................192
HowtoSpecifyPropertiesontheCommandLine................................................................193
Licenses.......................................................................................................................194
GNUGPL..............................................................................................................................194
CommercialLicenses............................................................................................................194
Contact............................................................................................................................195

8
Preamble

Preamble
J2MEdevelopersfaceaseriousproblem:eithertheyuseonlythelowestcommondenominatorof
J2MEdevicestheMIDP/1.0standardortheychoosetosupportonlyafewhandsets,forwhich
theyoptimizetheirapplicationswithalotofenergy.TheopensourcetoolJ2MEPolishpromisesa
solutiontothisproblemandmore.
J2MEPolishisactuallyawholecollectionofdifferenttoolsforwirelessJavaprogrammers.The
toolsrangefromstandardbuildtoolsforcompiling,preverifyingandpackagingtheapplicationstoa
sophisticatedoptionalGUIwhichcanbedesignedwithsimpleCSStextfiles.
Followingtoolsareincluded:
BuildTools/J2MEPolishTask:preprocessing,resourceassembling,localization,compilation,
preverification,obfucationandpackagingofJ2MEapplications.Youcanoptimizeyour
applicationformultipledevicesandlanguages/localesatthesametime.J2MEPolishcanalso
invokeanyemulatorsforyou.
DeviceDatabase:AnXMLbaseddevicedatabaseprovidesaconvenientandportablewayfor
adjustingyourapplicationtodifferentdevices.Togetherwiththepowerfulpreprocessing
capabilitiesyoucanusethisdatabasedirectlyinyourapplication.
LoggingFramework:Theloggingframeworkcanbeusedtoenableordisablelogginglevelsfor
classesorcompletepackagesjustbymodifyingsomesettingsinthecentralbuild.xml.Messages
whicharegivenoutwithSystem.out.println()canbeshownonrealdevicesaswell!Ofcourse
youcandisableallloggingcompletely,sothatnotracesareleftintheapplication.Thissaves
runtimeaswellasmemory.
AutomaticResourceAssembling:Allresourceslikeimagesandsoundfilesareassembled
automaticallyforyou.YoucanusespecificresourcesforvendorslikeNokiaorfordeviceswhich
supportaspecificformateasily.Youcanevenincluderesourcesonconditions,sothatMIDI
soundfilesareonlyincludedwhenthetargetdevicedoesnotsupportMP3butsupportstheMIDI
format,forexample.
Localization:It'seasytocreatelocalizedapplicationsjustprovidethetranslationsandifyou
likeotherlocalespecificresourcesandJ2MEPolishwillembedthemintotheapplication.In
contrasttoallothersolutions,localizedapplicationsdonothaveanoverheadcomparedwith
nonlocalizedapplications,sincethetranslationsareactuallyintegratedonthesourcecodelevel.
GUI:ThestandardJ2MEwidgetscannotbedesignedatall.WithJ2MEPolishyoucanusethe
standardMIDP/1.0aswellasMIDP/2.0widgetsinyourprogramanddesignthemwithsimple
CSSdirectiveslikebackground-image: url( bg.png );.Webdesignerscannowdesign
theapplicationindependentlyofprogrammersanddesignscanbeadjustedeasilyfordifferent
handsets.YoucanevenuseMIDP/2.0widgetsliketheCustomItemonMIDP/1.0phones!
Utilities:SomeoftenusedcomponentslikethefastArrayListortheTextUtilformanaging
fontbasedtextscanbeusedforsolvingdaytodayproblems.
GameEngine:WiththehighlyoptimizedgameengineyoucanusetheMIDP/2.0APIfor
MIDP/1.0devicesaswell.J2MEPolishtakescarefortheporting!YoucanalsoadjusttheAPI,
e.g.byspecifyingthatabackbufferoptimizationshouldbeusedforTiledLayeretc.

9
Preamble

StandaloneTools:Thebinarydataeditorcanbeusedforeditinganystructuredbinarydatafiles
muchmorecomfortablethanahexeditor.Anoftenneededfeatureareleveldatafiles,whichare
easytomanagewiththebinarydataeditor.Anothertoolisthebitmapfonteditor,whichcanbe
usedforcreatingbitmapfontsoutofanyTrueTypefonts.
ObviouslyyoucanalsoextendandusethemoreadvancedfeaturesoftheJ2MEPolishframework.
Youcanuseyourownwidgets,addyourownpreprocessor,orintegrateyourownobfuscatorwith
ease.
MigratingtoJ2MEPolishiseasy,sinceitisbasedonAnt.AntisthestandardforbuildingJava
applicationsandissupportedbyallIDEs.YoucaninvokeJ2MEPolisheitherfromwithinyourIDE
ofchoiceorfromthecommandline.
IhopeyoufindJ2MEPolishusefulandhavefunwithit!

Bremen/Germany,November2005

RobertVirkus/EnoughSoftware

10
IntroductiontoJ2MEPolish

IntroductiontoJ2MEPolish
ThischapterintroducesyoutosomeofthepossibilitiesofJ2MEPolish.Ifyouwanttoknow
specificdetails,pleaserefertothefollowingchapters.

Installation J2ME Polish: Overview


Editions:GPL(forOpenSource
J2MEPolishcontainsagraphicalinstallerwhichcanbe products),SingleLicense(199,valid
startedbydoubleclickingthedownloadedjarFileorby foroneJ2MEapplication),Runtime
callingjavajarj2mepolish[VERSION].jarfromthe License(199,validforanarbitrary
commandline,e.g.javajarj2mepolish1.1.jar. numberofapplicationswhichcanonly
beinstalleda100times),Enterprise
License(2990,validforanynumber
AnExampleApplication
ofapplications).Anadditional
Forthisintroductionweuseasimpleapplicationasan DeveloperSeatlicenseneedstobe
example.Theapplicationjustshowsasimplemenuwhich obtainedforeverydeveloper(99,).
istypicalformanyJ2MEapplications(listing1).Thisis OperatingSystems:Windows,Linux,
thesampleapplicationwhichisincludedintothe MacOSX
J2MEPolishdistribution. Prerequisites:JavaWirelessToolkit,
Ant
Listing 1: MenuMidlet.java BuildProcess:preprocessing,device
public class MenuMidlet extends MIDlet { optimization,resourceassembling,
localization,devicedatabase,
List menuScreen;
compiling,preverifying,obfuscating,
public MenuMidlet() { signingofMIDlets,creationofjarand
super(); jadfiles
System.out.println("starting MenuMidlet");
GUI:DesignviaCSS,100%compatible
this.menuScreen = new List("J2ME Polish",
List.IMPLICIT); totheMIDPstandard,optional.
this.menuScreen.append("Start game", null); GameEngine:MIDP/2.0gameAPIfor
this.menuScreen.append("Load game", null);
MIDP/1.0devices.
this.menuScreen.append("Help", null);
this.menuScreen.append("Quit", null); www.j2mepolish.org
this.menuScreen.setCommandListener(this);
System.out.println("intialisation done.");
}

protected void startApp() throws BuildingtheApplication


MIDletStateChangeException {
System.out.println("setting display."); TobuildtheapplicationwithJ2MEPolishwe
Display.getDisplay(this).setCurrent(
this.menuScreen ); needtocreateafilecalledbuild.xmlwhich
} controlsthebuildprocess.Thisisastandard
[...]
Antfile,somostIDEssupporttheeditingof
thisfilewithsyntaxhighlighting,auto
completionetc.Don'tworryifyouhavenever
workedwithAntbeforealthoughitcanlookquitescaryatthebeginningitiseasytomasterafter
awhile.Thebuild.xmlfileisalsoincludedintheJ2MEPolishdistribution,themainpartsofitare
showninlisting2.Tobuildthesampleapplication,weneedtorightclickthebuild.xmlwithinthe
IDEandselectExecute,RunAnt...ormakedependingontheIDE.Thebuildprocesscan
alsobestartedfromthecommandline:entertheinstallationdirectoryandtypetheantcommand.
J2MEPolishnowpreprocesses,compiles,preverifiesobfuscatesandpackagesthecode
automaticallyforanumberofdevices.Theresultingapplicationbundlescanbefoundinthedist

11
IntroductiontoJ2MEPolish

folderafterJ2MEPolishfinishedthebuild.
Listing 2: build.xml
Tounderstandandcontrolthebuildprocess, <project name="example" default="j2mepolish">
weneedtohaveacloserlookatthe
<property name="wtk.home" value="C:\wtk2.1">
build.xml(listing2):
<taskdef name="j2mepolish"
AtfirsttheJ2MEPolishAnttaskneedsto classname="de.enough.polish.ant.PolishTask"
bedefinedwiththe<taskdef>construct. classpath="import/enough-j2mepolish-
build.jar:import/jdom.jar:import/proguard.jar
TheAntpropertywtk.homepointstothe "/>
installationdirectoryoftheWireless
Toolkit. <target name="j2mepolish">
<j2mepolish>
TheJ2MEPolishtaskhasthethreemain <info
name="SimpleMenu"
sections<info>,<deviceRequirements> version="1.0.0"
and<build>.The<info>element description="A test project"
jarName="${polish.vendor}-${polish.name}-
specifiessomegeneralinformationaboutthe example.jar"
projectlikethenameandtheversion.The jarUrl="${polish.jarName}"
</info>
<deviceRequirements>elementisusedto <deviceRequirements>
selectthedevicesforwhichtheapplication <requirement name="JavaPackage"
value="nokia-ui" />
shouldbebuilded.The<build>elementis </deviceRequirements>
thecentralcontrolleroftheactualbuild <build
process.Thiselementcontrolswhetherthe fullscreen="menu"
usePolishGui="true"
J2MEPolishGUIshouldbeused,what <midlet class="MenuMidlet" name="Example"/>
MIDletsareused,whichobfuscatorsshould </build>
</j2mepolish>
beused,andsoon.Hereyoucanalsodefine </target>
additionalvariablesandsymbolswhichcan </project>
beusedinthepreprocessingstep.
Youcanalsousetheadditionalsection<emulator>forlaunchinganyWTKbasedemulatorsfrom
withinJ2MEPolish.

DesigningtheApplicationwithCSS
EventhoughtheapplicationjustusesplainMIDPcode,wecanusetheJ2MEPolishGUIbysetting
theusePolishGuiattributeofthe<build>elementtotrue(listing2).J2MEPolishthenweaves
thenecessarycodeandAPIsintotheapplicationautomatically.Forspecifyingorchangingthe
design,thefilepolish.cssinthefolderresourcesneedstobecreatedorchanged(listing3).As
youmighthaveguessed,thisfileisincludedintheJ2MEPolishdistributionaswell.
Thepolish.cssfilecontainsthestyledefinitionsforallitemsandscreensoftheapplication.First
wedefinetheusedcolorsinthecolorssection.Bydoingsowecanlaterchangethecolorsofthe
completeapplicationinoneplace.
Thetitlestyleisusedfordesigningthescreentitles.Thefocusedstyleisusedfordesigning
thecurrentlyfocuseditem,e.g.ofaformoralist.
Aswehavenotusedany#stylepreprocessingdirectivesinthecode,weneedtousedynamic
styleselectorslikelistandlistitemfordesigningtheapplication.Allsettingsspecifiedinthe
liststyleareusedfordesigningscreensofthetypelist.Andallsettingsspecifiedinthe
listitemstyleareusedforitemswhichareembeddedinalist.

12
IntroductiontoJ2MEPolish

Allstylessupportthecommonattributesmargin, Listing 3: polish.css


padding,layout,font,backgroundandborderas
colors {
wellasthespecialattributesbeforeandafter.Most bgColor: rgb(132,143,96);
itemsdoalsosupportspecificattributes. brightBgColor: rgb(238,241,229);
brightFontColor: rgb(238,241,229);
Theliststyleintheexampleutilizesthespecific fontColor: rgb( 30, 85, 86 );
}
attributecolumnsforspecifyingthatatablewith
twocolumnsshouldbeusedforthelist(figure1). title {
padding: 2;margin-bottom: 5;
Designsand font-face: proportional; font-size:
large; font-style: bold; font-color:
resourceslike brightFontColor;
imagesandsoon background: none; border: none;
canbeadjustedto layout: center | expand;
}
differentdevicesby
placingtheminto focused {
padding: 5;
theappropriate background {
subfolderofthe type: round-rect; arc: 8; color:
brightBgColor; border-color:
resourcesfolder. fontColor; border-width: 2;
Forusingadifferent }
designforNokia font {
style: bold; color: fontColor;
phonesyoucanadd size: small;
thefileresources/ }
Fig.1:Thedesignedsample layout: expand | center;
application. Nokia/polish.css }
andforusinga
list {
specialdesignfortheNokia/6600phoneyoucan padding: 5; padding-left: 15; padding-
addthefileresources/Nokia/6600,etc.Thesame right: 15;
background {
istrueforotherresourceslikeimagesorsound color: transparent;
files.Theresourceassemblingdoeswork image: url( bg.png );
independentlyoftheusageoftheJ2MEPolishGUI }
layout: expand | center | vertical-
bytheway. center;
columns: 2;
Whenanapplicationhasmorethanonescreenand }
thescreensshouldhavedifferentdesigns,oneneed
listitem {
tousestaticstyles.Incontrasttodynamicstyles, margin: 2; padding: 5; background:
staticstylesareaddedduringthecompilationphase none; font-color: fontColor; font-
andare,therefore,fasterandmorememory style: bold; font-size: small;
layout: center;
efficient.Staticstyles,however,needchangesinthe icon-image: url( icon%INDEX%.png );
applicationcode: icon-image-align: top;
}
Forusingastaticstyle,the#stylepreprocessing
directiveisused.Thisdirectivecanbeplacedbeforeanyconstructorofascreenoranitem(and
somemoreplacesliketheListappend()methods)withinthecode.
public MenuMidlet() {
super();
System.out.println("starting MenuMidlet");
//#style mainScreen
this.menuScreen = new List("J2ME Polish", List.IMPLICIT);
//#style mainCommand
this.menuScreen.append("Start game", null);
//#style mainCommand

13
IntroductiontoJ2MEPolish

this.menuScreen.append("Load game", null);


//#style mainCommand
this.menuScreen.append("Help", null);
//#style mainCommand
this.menuScreen.append("Quit", null);
//#style mainCommand
this.menuScreen.setCommandListener(this);
System.out.println("intialisation done.");
}
Insteadofusingthelistandthelistitemstylesinthepolish.css,younowneedtousethestyles
mainCommandandmainScreen.Sincethesearestaticstyles,theyneedtostartwithadotinthe
polish.cssfile:
.mainScreen {
padding: 5; padding-left: 15; padding-
[...]
}

.mainCommand {
margin: 2; padding: 5; background:
[...]
}
Withusingthe#stylepreprocessingdirectivethecodestillremains100%compatibletotheMIDP
standard,sooneusethenative/standardGUIforveryolddeviceswhileusingtheJ2MEPolishGUI
formoderndevicesatthesametime.
Youcanspecifyinthebuild.xmlfilewhatresourcesfoldershould
beused.Thismechanismcanbeusedtocreatedifferentdesignsof
oneapplication.Figure2showsthesampleapplicationwitha
differentdesign.ThisdesignisalsoincludedintheJ2MEPolish
distributionandcanbeusedwhentheresDirAttributeissetto
resources2inthebuild.xml.

DebuggingandLogging
LogginganddebuggingiscomplexanddifficulttaskunderJ2ME.
Ononehandloggingmessagesneedmemoryaswellascomputing
timeandontheotherhandtherearenologgingframeworkslike Fig.2:Thesameapplicationwith
log4javailableforJ2ME.ThisiswhyJ2MEPolishincludessucha anotherdesign.Thebackgroundis
frameworkwiththesefeatures: actuallyanimated:itstartswhite
andditherstotheshownpink.
Logginglevelslikedebug,info,warn,erroretc.canbedefined
forsingleclassesorpackages.
Userdefinedlevelscanbeused,too.
Loggingmessagescanbeviewedonrealdevicesaswell.
Loggingmessageswhicharenotactive,willnotbecompiledanduse,therefore,noresourcesat
all.
Thecompleteloggingcanbedeactivated.
SimpleSystem.out.println()callsareusedforlogging.
Theloggingiscontrolledwiththe<debug>elementinthebuild.xmlfile:

14
IntroductiontoJ2MEPolish

<debug enable="true" showLogOnError="true" verbose="false" level="error">


<filter pattern="com.company.package.*" level="info" />
<filter pattern="com.company.package.MyClass" level="debug" />
</debug>
Theenableattributedefineswhetherloggingshouldbeactivatedatall.The
showLogOnErrorattributecanbeusedforshowingthelogautomatically,wheneveranerrorhas
beenlogged.ThisonlyworkswhentheGUIofJ2MEPolishisused,though.Anerrorcanbelogged
justbyappendingtheerrorobjecttoaSystem.out.println()call:
try {
callComplexMethod();
//#debug info
System.out.println( "complex method succeeded." );
} catch (MyException e) {
//#debug error
System.out.println( "complex method failed" + e ); // when showLogOnError is true
} // this will trigger the log
Whentheverboseattributeistrue,aftereachloggingmessagethecurrenttimeandthesource
codefileaswelllineofthemessagewillbeadded.Thiseasesthelocationoferrorsespeciallywhen
obfuscationisused.TheJ2MEAPIsofJ2MEPolishwillalsospecifydetailsoferrorswhenever
theythrowanexception,whentheverboseattributeistrue.Thelevelattributecontrolsthe
generallogginglevelwhichisusedwhennospecificlevelhasbeenassignedforaclass.The
logginglevelsarehierarchicallyordered:
debug<info<warn<error<fatal<userdefiniert
Whenaclasshasthelogginglevelinfoassigned,messageswithalevelofwarn,errorandso
onwillalsobelogged,butnodebugmessages.
Inthesourcecodeloggingmessageswillbeintroducedwiththe#debugpreprocessingdirective,
whichcanspecifythelogginglevel,e.g.//#debuginfo.Whennolevelisspecifiedthedebug
levelisassumed.

EasyDeviceOptimizationswithPreprocessingandtheDeviceDatabase
Deviceoptimizationsaremostlyneededfortheuserinterfaceofanapplication.TheUIof
J2MEPolishadaptsautomaticallytodevicesandcanthankstotheresourceassemblingbe
easilyadjustedtodifferentdevicesanddevicegroups.
Therearehowever,othersituationsinwhichdeviceoptimizationsareuseful.Withthehelpofthe
preprocessingcapabilitiesanddevicedatabaseofJ2MEPolish,theseoptimizationsaredoneeasy
andwithoutriskingtheportabilityoftheapplication.
Oftenthepreprocessingdirectives#ifdef,#ifand#=areusedforoptimizations:
WhenanAPIisrequiredforaspecificfunctionality,justusethepolish.api.[apiname]symbol,
whichisdefinedforeachsupportedAPI:
//#if polish.api.mmapi
// this device supports the Mobile Media API
[...]
//#else
// this support does not support the mmapi
[...]
//#endif

15
IntroductiontoJ2MEPolish

OnecandifferentiatebetweenMIDPversionswiththepolish.midp1andthepolish.midp2
symbol:
//#if polish.midp2
// this device supports MIDP/2.0 standard
[...]
//#else
// this support does support the MIDP/1.0 standard
[...]
//#endif

TodistinguishbetweentheCLDC/1.0andtheCLDC/1.1standard,thepolish.cldc1.0and
polish.cldc1.1symbolscanbeused:
//#if polish.cldc1.1
float f = 1.2f;
[...]
//#endif

Severalrequirementscanbecombined,too:
//#if polish.api.mmapi || polish.midp2
// this device supports at least the basic Mobile Media API
[...]
//#endif

Onecancomparevariablesaswell:
//#if polish.BitsPerPixel >= 12
// this device uses at least 12 bits per pixel.
//#endif
//#if polish.Vendor == Nokia
// this is a Nokia device
//#endif

Variablescanbedefinedaswellandbeusedwithinthesourcecode.AnURLcouldbedefinedin
thebuild.xmllikethis:
<variables>
<variable name="update-url" value="http://www.enough.de/update" />
</variables>
Thedefinedvariablecanbeusedinthesourcecodewiththe#=directive:
//#ifdef update-url:defined
//#= public static final String UPDATE_URL = "${ update-url }";
//#else
// no variable definition was found, use a default-value:
public static final String UPDATE_URL = "http://default.com/update";
//#endif

FunFunFun:TheGameEngine
ThegameengineofJ2MEPolishletsyouusetheGameAPIoftheMIDP/2.0standardfor
MIDP/1.0devicesaswell.Nochangesinthesourcecodearenecessary,sincethenecessaryAPIis
weavedintotheapplicationautomaticallyforMIDP/1.0devices.
ThecompleteAPIcanbeused:Sprite,GameCanvas,TiledLayer,LayerManagerandLayer.The

16
IntroductiontoJ2MEPolish

currentlimitationsarethatnopixellevelcollisiondetectionsandnospritetransformationsfornon
Nokiadevicesaresupported(forNokiadevicesspritetransformationsaresupported).
Thegameenginecanbeoptimizedforseveralusagescenarios,youcanspecifythatthebackbuffer
optimizationshouldbeusedfortheTiledLayerimplementation,forexample.

ExtendingJ2MEPolish
J2MEPolishcanbeextendedinseveralways:
BuildTools:
Obfuscator:integrateyourown(orathirdparty)obfuscator
Preprocessing:addyourownpreprocessingdirectives
Youcanalsousethe<java>elementtoextendJ2MEPolish
GUI:
BackgroundsandBorders:custombordersorbackgroundsenhancethepossibilities
Items:extendandusestandardCustomItemsanddesignthemusingCSS
HowtheseextensionsareimplementedisdescribedintheExtendingJ2MEPolishChapteron
page157.
The<java>elementisdescribedonpage59.

17
Installation

Installation
Requirements
TouseJ2MEPolish,followingcomponentsneedtobeinstalled:
Java2StandardEditionSDK1.4orhigher,http://java.sun.com/j2se/1.4.2/index.jsp
JavaWirelessToolkit,http://java.sun.com/products/j2mewtoolkit/index.html,
or http://mpowers.net/midp-osx/ forMacOSX
FavoriteIDE,forexampleEclipse3.0,http://www.eclipse.org
Ant1.5orhigher,ifnotalreadyintegratedintheIDE,http://ant.apache.org

InstallationofJ2MEPolish
ForinstallingJ2MEPolishdownloadthelatestreleaseandstarttheinstallationeitherbydouble
clickingthefileorbycalling"javajarj2mepolish$VERSION.jar"fromthecommandline(where
$VERSIONdenotesthecurrentversionofJ2MEPolish).
TheinstallerofJ2MEPolishcontainsasampleMIDletapplicationwithtwodifferentdesigns.This
applicationisoptimizedforNokiaSeries60devices,soitisrecommendedtohavesuchanemulator
installed.TheNokiaemulatorcanberetrievedfromhttp://forum.nokia.com.
Tobuildthesampleapplication,runtheincludedsample/build.xmlfromyourfavoriteJavaIDE
orcall"ant"fromthecommandline,afteryouhaveswitchedtothesampledirectory.Call"ant
testj2mepolish"toskiptheobfuscationandtoincludedebuginformationofthesampleapplication.
Alsothedefaultemulatorislaunchedwiththeapplication.

UpdatingJ2MEPolish
Whenyouwanttoupdateanexistinginstallation,youdonotneedtoreinstallthewholepackage.
Forsavingbandwidthyoucandownloadjusttheupdatepackage.Thispackagecontainsthetwo
JARfilesenoughj2mepolishbuild.jarandenoughj2mepolishclient.jarwhichneedtobe
copiedintothe"import"folderofyourinstallationdirectory.

IntegratingJ2MEPolishintoEclipse
TointegrateJ2MEPolishintoEclipsetheeasiestwayistocopyoneofthesampleapplications
(fromthesamplesfolderofyourJ2MEPolishinstallation)inyourworkspace,forexamplethe
menuapplication.ThenstartEclipseandcreateanewprojectcalled"application".Eclipsethen
automaticallyintegratesallsourcefilesandsetstheclasspath.Youshouldfindthesample
applicationnowinthePackageExplorer(packagede.enough.polish.example).
Ifthesourceshavenotbeenintegratedautomatically,setthesourcedirectoryoftheprojecttothe
srcdirectory:SelectProject>Properties...>JavaBuildPath>Sourceandaddthe
sourcefoldersrcthere.
Whentheclasspathwasnotsetcorrectly,pleaseincludethefollowingjarfilesfromthe
${polish.home}/importfoldertoyourclasspath:import/midp2.jar,import/enoughj2mepolish
client.jar,import/mmapi.jar,import/nokiaui.jar,import/wmapi.jar.Actuallyonlythefirsttwo

18
Installation

librariesareneededforthesampleapplication,butwhentheothersareincluded,future
enhancementsareeasiertoaccomplish.
Optionallyyoucanchangethebuildsettingsbymodifyingthefile"build.xml"(whichislocatedin
therootofthesampleproject).ForexampleyoucanchangethedeviceRequirementsifyouwantto.
TheexampleisoptimizedtoNokiaSeries60devices.
YoucannowcreatetheJARandJADfilesbyrightclickingthebuild.xmlfile,selecting"Run
Ant"andrunningAntinthenextdialog.YouwillfindtheJARandJADfilestheninthe"dist"
folderoftheproject.IfyouwanttoaccessthemfromwithinEclipse,youmightneedtorefreshyour
project:Rightclicktheprojectandselect"Refresh".
IftheRunAnt...commandisnotshown,selectthebuild.xmlfile,thenopentheMenuRun
andselectExternalTools>Runas>AntBuild.
AfteryouhaveintegratedthesampleapplicationintoEclipse,youwillfindfollowingstructurein
yourproject(assumingthatyourprojectiscalledsampleandyourworkspaceworkspace):

Folder/File Description
workspace/sample Theapplicationsproject
workspace/sample/build.xml Thecontrollerofthebuildprocess
workspace/sample/resources Folderforallresourcesanddesigndescriptionsoftheproject
workspace/sample/resources/polish.css Basicdesigndescription
workspace/sample/build Temporarybuildfolder,willbecreatedautomatically.Shouldnot
besharedinCVSandsimilarsystems.
workspace/sample/dist Folderforthereadytodeployapplications.Itwillbecreated
automatically.ShouldnotbesharedinCVSandsimilarsystems.

IntegratingJ2MEPolishintoBorland'sJBuilder
TointegrateJ2MEPolishintoJBuilderitisbesttocopythesampleapplication(thesample
folderofyourJ2MEPolishinstallation)inyourworkspace.ThenstartJBuilderandcreateanew
projectcalled"sample".
Intheprojectdialogselecttheappropriatepathandconfirmthesrcfolderasthemainsource
folder.SwitchtotheRequiredLibrariestabandselectAdd...andthenNew....EnterMIDP
Developmentorsimilarasthenameofthelibraryandaddthefilesenoughj2mepolishclient.jar,
midp2.jar,mmapi.jar,wmapi.jarandnokiaui.jarfromthe${polish.home}/importfolder
tothelibrarypath.
Note:onlythefirsttwofilesareactuallyneededbythesampleapplication,butifyoulaterwantto
explorethefullpossibilitiesofJ2MEPolishyoualreadyhaveallimportantlibrariesincluded.
Nowcreatethenewproject.
Aftertheprojecthasbeencreated,youneedtointegratetheprovidedbuild.xmlfile:Select
Wizard>Ant>Add...andselectthefilebuild.xmlintheprojectroot.Nowthe
build.xmlisshownintheprojectview.Important:youneedtodeactivatetheBorlandcompiler

19
Installation

forbuildingtheactualapplications:Rightclickthebuild.xmlfile,selectProperties...andde
selecttheUseBorlandJavacompilercheckbox.
Youcannowbuildthesampleapplicationbyrightclickingthebuild.xmlfileandselecting
Make.YouwillfindthecreatedJ2MEapplicationfilesinthedistfolderofyourproject,after
youhaveswitchedtotheFileBrowserview.

IntegratingJ2MEPolishintoNetBeans

NetBeans3.6
ForintegratingJ2MEPolishwithNetBeans3.6mounttheinstallationdirectoryofyourJ2ME
Polishinstallation,rightclickthe"sample/build.xml"fileandchoose"Execute".
CreateaNewProject:Goto"Project">"ProjectManager"andselect"New..."andcallthenew
project"j2mepolish".
MountingtheFilesystem:Select"File">"MountFilesystem...">"LocalDirectory"andselect
thefolderintowhichyouhaveinstalledJ2MEPolish.
Note:Don'tnavigateintothedirectory.JustselecttheJ2MEPolishdirectoryandclick"Finish".
ExecutingJ2MEPolish:Openthemountedfilesystem(switchtothefilesystemwindowby
pressing"Control2"),locatethefile"sample/build.xml",rightclickitandselect"Execute".
Aftertheexecutionyouwillfindthecreatedapplicationsinthe"dist"folder.
MountingtheLibraries:Openthemountedfilesystem,openthe"import"directoryandright
clickthe"enoughj2mepolishclient"jarandselect"MountJAR".Dothesamewiththelibraries
"midp2","mmapi","nokiaui"and"wmapi".
OpentheSampleApplication:Youcannowchangethesampleapplication,ifyouwantto.You
canfinditinthe"sample/src"directory(inthepackage"de.enough.polish.example").

NetBeans4.x
ForintegratingJ2MEPolishwithNetBeans4.0createanewprojectandcopythesampleproject
from${polish.home}/sampleintoyournewprojectwithafilemanager.Rightclickthebuild.xml
andchoose"RunTarget">"j2mepolish"forrunningtheexample.
Createanewproject:Goto"File">"NewProject"andselect"Mobile">"Mobile
Application"asyourprojecttype.Givetheprojectanynameandchooseanyfolderasthe
project'shome.Deselectthe"CreateHelloMIDlet"optionandselect"Finish"tocreatethe
project.
Copythesampleproject:Navigatetothe"${polish.home}/sample"directorywithyourfile
manager(e.g.WindowsExploreronWindowsorFinderonMacOSX).Selectthe"resources",
"resources2"and"src"foldersaswellasthe"build.xml"fileandcopyallintothefolderofyour
NetBeansproject.Overwriteanyexistingfiles.
ReturntoNetBeans,rightclickyournewprojectinthe"Projects"viewandselect"Refresh
Folders".Youcannowviewthesampleapplicationinthe"de.enough.polish.example"package.
Rightclickyourprojectagainandselect"Properties".Goto"Build"andselect"Librariesand
Resources".Select"AddJar/Zip"andaddthe"${polish.home}/import/enoughj2mepolish

20
Installation

client.jar"filetoyourproject.
Nowswitchtothe"Files"viewandrightclickthe"build.xml"file.Select"RunTarget">
"Advanced".Write"test,j2mepolish"inthefollowingdialog,sothatthe"test"targetisexecuted
first,followedbythe"j2mepolish"target.J2MEPolishnowexecutesandstartstheWTK
emulator.

NetBeans5.x
J2MEPolishprovidesNetBeansspecificbuildscriptsfromJ2MEPolish1.3Beta3onwards.You
cannowjustopenanyoftheprovidedsampleapplications,deletethedefaultbuild.xmlscriptand
renamethebuildnetbeans.xmlscripttobuild.xml.Youcanfromthenonusethenormaldebugging,
buildandcompilefacilitiesofNetBeans.
IntegratingasampleapplicationinNetBeans:
SelectFile>OpenProject...andselectanysampleapplicationin${polish.home}/samples.Just
selectafolderlikethemenufolderandselectOpen.
NowswitchtotheFileswindowbyselectingWindow>Files.
Inthiswindowdeleteorrenamethebuild.xmlscriptwhichisinthebasefolderoftheproject.
Nowrightclickthebuildnetbeans.xmlscriptandrenameittobuild.xml.Whentherenaming
doesnotwork,doitdirectlyfromthefilesystem(e.g.WindowsExplorer).
Fromnowonyoucanbuild,run,debugandcompilewiththenormalNetBeanscommands(e.g.
F5fordebugging).J2MEPolishisthenusedforbuildingetc.
WhenyoustartanewprojectinNetBeans,justcopyoneofthesamplebuild.xmlscriptstoyour
project'sfolder.Thenadjustthesettingsaccordingtoyourneeds.

SetupandConfigurationofAnt
Antonlyneedstobeconfiguredwhenitshouldbecalledfromthecommandline.SinceAntis
integratedineverymodernJavaIDE,youjustneedtorightclickthebuild.xmlfileinyourIDE
andchooseRunAnt...(orsimilar).
AfteryouhavedownloadedandinstalledAnt(http://ant.apache.org),youneedtosetyourPATH
environmentvariable,sothattheantcommandcanbefound.IfyouhaveinstalledAntinto
C:\tools\antthenenterfollowingcommandonyourWindowscommandline(oryourshell
script):
SET PATH=%PATH%;C:\tools\ant\bin

YoucanchangethePATHvariablepermanentlyintheSystemSettingsofWindows(ControlCenter
>System>Advanced>Environmentvariables).
NowyouneedsettheJAVA_HOMEvariableaswell,e.g.:
SET JAVA_HOME=C:\j2sdk1.4.2

UnderUnix/Linux/MacOSXpleaseusetheexportcommandinsteadoftheSETcommand.
Nowyoushouldbeabletoissuefollowingcallsfromthecommandline(makesurethatyouarein

21
Installation

thesamplefolderofyourJ2MEPolishinstallation):
echo Just calling ant to build and obfuscate the example:
ant
echo Now calling ant with the test-property set to true, so the build is faster:
ant test j2mepolish

IntegratingJ2MEPolishwithanExistingProject
YoucanuseJ2MEPolishforanyexistingprojectbycopyingthefile"sample/build.xml"aswellas
the"sample/resources"foldertotherootfolderoftheproject.Youthenneedtoadjustthe
"build.xml"andthe"resources/polish.css"files.
Herearetherequiredsteps:
Copythe"sample/build.xml"andthe"sample/resources"foldertoyourprojectroot.
Moveyourresourceslikeimages,soundfilesetcintotheresourcesfolderofyourproject.
Rememberthatyoucannotusesubfoldersforresources,sincesubfoldersareusedforthe
automaticresourceassemblingofJ2MEPolish(seepage67).
Adjustthe"build.xml"file:youneedtospecifyyourMIDletclassinthe<midlet>element.You
mightalsowanttoadjustthe<deviceRequirements>element,currentlyapplicationsarebuildfor
4devicegroups:
1)NokiaSeries60("Nokia/Series60"),
2)NokiaSeries60withMIDP/2.0("Nokia/Series60Midp2"),
3)AnyMIDP/1.0phone("Generic/midp1"),
4)AnyMIDP/2.0phone("Generic/midp2").
IfyouwanttousetheJ2MEPolishGUI,youneedtomakechangestothe"resources/polish.css"
file.
Tip:usedynamicstyleslike"form"and"list"forastart.Havealookatthehowtoexplainingthe
firststepsforusingtheJ2MEPolishGUIonpage187.
IfyoudonotwanttousetheJ2MEPolishGUI,disableitbysettingthe"usePolishGui"attribute
ofthe<build>elementto"false".
EnsurethatyourAntsetupiscorrect,doyouhavesettheJAVA_HOMEenvironmentvariable?
Callantwithinyourprojectroottobuildyourapplication.

22
TheDeviceDatabase

TheDeviceDatabase
AllJ2MEdevicesaredefinedinthefiledevices.xml.Everydevicehasavendor,whichisdefined
inthefilevendors.xml.Everydevicecanbelongtoanarbitrarynumberofgroups,whichare
definedinthefilegroups.xml.Librariescanbemanagedusingthefileapis.xml.
Allthesefilesarecontainedinthefileenoughj2mepolishbuild.jar,sowhenyoudonotfind
them,extractthemfromthejarfileintotherootfolderoftheproject.

vendors.xml
ThevendorsofJ2MEdevicesaredefinedinvendors.xml.Anexampledefinitionis:
<vendors>
<vendor>
<name>Nokia</name>
<features></features>
<capability name="colors.focus" value="0x5555DD" />
</vendor>
<vendor>
<name>Siemens</name>
</vendor>
</vendors>

Inthiscode2vendorsaredefinedNokiaandSiemens.Vendorscanpossessfeaturesand
capabilities,whichareinheritedbyalldevicesofthatvendor.Theseabilitiescanbeusedduringthe
preprocessing(comparechapterTheworldofpreprocessing,page78).Featuresarejustacomma
separatedlist,whereascapabilitiesalwayshaveanameandavalue.
Youcandefineyourownvendorsinthecustomvendors.xmlfile.Thisallowsyoutouseyourown
vendorswithoutneedingtomergethevendors.xmlfilewitheachupdateofJ2MEPolish.The
customvendors.xmlfileisloadedfromthecurrentprojectfolderandifthatfiledoesn'texist
fromtheJ2MEPolishinstallationfolder.

groups.xml
Thedevicegroupsaredefinedinthefilegroups.xml.Adevicecanbeamemberinanynumberof
groups.
<groups>
<group>
<name>Nokia-UI</name>
<features></features>
<capability name="classes.fullscreen"
value="com.nokia.mid.ui.FullCanvas" />
<capability name="JavaPackage" value="nokia-ui" />
</group>
<group>
<name>Series60</name>
<parent>Nokia-UI</parent>
<capability name="JavaPlatform"
value="MIDP/1.0" />
</group>
</groups>

23
TheDeviceDatabase

ThegroupNokiaUIisusedfordeviceswhichsupporttheUIAPIofNokia.Thegroup
Series60extendsthisgroup.Anycapabilitiesorfeaturesdefinedinthegroupscanbeoverridden
orcompletedbythedevicedefinitions.
Youcandefineyourowngroupsinthecustomgroups.xmlfile.Thisallowsyoutouseyourown
groupswithoutneedingtomergethegroups.xmlfilewitheachupdateofJ2MEPolish.The
customgroups.xmlfileisloadedfromthecurrentprojectfolderandifthatfiledoesn'texist
fromtheJ2MEPolishinstallationfolder.

devices.xml
Indevices.xmlallJ2MEdevicesaredefined.
<devices>
<device>
<identifier>Motorola/i730</identifier>
<user-agent>MOTi730</user-agent>
<capability name="SoftwarePlatform.JavaPlatform"
value="MIDP/2.0" />
<capability name="HardwarePlatform.ScreenSize"
value="130x130" />
<capability name="HardwarePlatform.BitsPerPixel"
value="16" />
<capability name="HardwarePlatform.CameraResolution"
value="300x200" />
<capability name="SoftwarePlatform.JavaProtocol"
value="UDP, TCP, SSL, HTTP, HTTPS, Serial" />
<capability name="SoftwarePlatform.JavaPackage"
value="wmapi, mmapi, motorola-lwt, location-api" />
<capability name="SoftwarePlatform.HeapSize"
value="1.15 MB" />
<capability name="SoftwarePlatform.MaxJarSize"
value="500 kb" />
</device>
<device>
<identifier>Nokia/6600</identifier>
<user-agent>Nokia6600</user-agent>
<groups>Series60</groups>
<features>hasCamera</features>
<capability name="ScreenSize" value="176x208"/>
<capability name="BitsPerPixel" value="16"/>
<capability name="JavaPackage" value="mmapi, btapi, wmapi" />
<capability name="JavaPlatform" value="MIDP/2.0" />
</device>
</devices>
IntheexampletheMotorolaIdent730andtheNokia6600aredefined.Capabilitiescanbegrouped
intohardwareandsoftwarecapabilities.Thisgroupingisoptionalandwillnotbedistinguishedin
thepreprocessingstep,thusonecannotusethesamenameforaSoftwarePlatformanda
HardwarePlatformcapability.
Theidentifierconsistsofthevendoranddevicename.Thestructureis[vendor]/[devicename].
The<features>elementdefinespreprocessingsymbols.Thesecanbecheckedinthesourcecodefor
examplewith//#ifdef[symbolname].Severalfeaturesneedtobeseparatedbycomma:
<features>hasPointerEvents, hasPointerEvents</features>
Groupscanbedefinedexplicitlywiththe<groups>element.Allgroupnamestowhichthedevice

24
TheDeviceDatabase

belongsareinacommaseparatedlist:
<groups>Series60, SomeGroup</groups> defines2groupsforthedevice.Groupscanalsobe
definedindirectlybythecapabilitiesofthedevice.
The<device>ElementsupportsthesingleattributesupportsPolishGui:
<device supportsPolishGui="true">...
NormallyitiscalculatedwhetheradevicesupportstheJ2MEPolishGUI:whenithasacolordepth
ofatleast8bitsperpixelandaheapsizeof500kbormore,thedevicesupportstheGUI.The
supportsPolishGuiattributeoverridesthiscalculation.
Youcandefineyourowndevicesinthecustomdevices.xmlfile.Thisallowsyoutouseyourown
deviceswithoutneedingtomergethedevices.xmlfilewitheachupdateofJ2MEPolish.The
customdevices.xmlfileisloadedfromthecurrentprojectfolderandifthatfiledoesn'texist
fromtheJ2MEPolishinstallationfolder.

apis.xml
Thefileapis.xmldefinessomecommonlibraries.YoudonotneedtoaddeveryAPIyouoryour
devicesupports,butifaAPIisknownunderseveralnames,itisadvisedtoaddthatAPIto
apis.xml.
<apis>
<api>
<name>Nokia User Interface API</name>
<description>The Nokia User Interface API provides
some advanced drawing functionalities.
</description>
<names>nokia-ui,nokiaui, nokiauiapi</names>
<files>nokia-ui.jar, nokiaui.zip</files>
<path>import/nokia-ui.jar</path>
</api>
<api>
<name>Bluetooth API</name >
<description>The Bluetooth API provides
functionalities for data exchange with other bluetooth
devices.
</description>
<names>btapi,bt-api, bluetooth, bluetooth-api</names>
<files>j2me-btapi.jar, bluetooth.zip</files>
<path>import/j2me-btapi.jar</path>
</api>
</apis>

Intheaboveexampletwolibrariesaredefined.The<name>elementdescribesthedefaultnameofa
library,whereasthe<names>elementdefinesotherpossiblenamesofthelibrary.The<files>
elementdefinesthenamesofthelibraryonthefilesystem.The<path>elementjustdefinesthe
defaultpath.Whenthatpathisnotfound,J2MEPolishtriestofindtheAPIwiththehelpofthe
filenamesdefinedinthe<files>element.
Youcandefineyourownlibrariesinthecustomapis.xmlfile.Thisallowsyoutouseyourown
librarieswithoutneedingtomergetheapis.xmlfilewitheachupdateofJ2MEPolish.Thecustom
apis.xmlfileisloadedfromthecurrentprojectfolderandifthatfiledoesn'texistfromtheJ2ME
Polishinstallationfolder.

25
TheDeviceDatabase

ExtendingtheDevicDatabase
Youcanextendthedevicedatabasebyeithermodifyingthecustomdevices.xml,custom
vendors.xml,customgroups.xmlandcustomapis.xml.Youcanstorethesefileseitherintheroot
directoryofyourproject(thesameplacewherethebuild.xmlfilelives)orinthe${polish.home}
directory.TheadvantageofstoringthefilesintheinstallationdirectoryofJ2MEPolishisthatyou
alwayshavetheverysamedevicedefinitions.Thedisadvantageisthatyouneedtobackupthese
fileswhenyouupgradeyourJ2MEPolishinstallation.
PleaseconsidertosubmityourchangestotheJ2MEPolishcommunitybysendingthemto
j2mepolish@enough.de.

DeviceCapabilities
ThedevicedatabaseofJ2MEPolishsupportsanumberofcapabilities,whichareusefulfor
preprocessingandtheassemblingofresources.
Youcanusecapabilitieswithanyname,butfollowingcategoriesarepredefined:

Capability Explanation PreprocessingAccess Groups


BitsPerPixel Colordepth:1ismonochrome, Variable: At8bitsperpixelfor
4are16colors, polish.BitsPerPixel, example:
8=256colors, BitsPerPixel.4+
Symbols:
16=65.536colors, and
polish.BitsPerPixel.1or
24=16.777.216colors BitsPerPixel.8
polish.BitsPerPixel.4,
polish.BitsPerPixel.16etc
ScreenSize Widthtimesheightofthe Variables: Respectivelythescreen
screenresolutioninpixels,e.g. polish.ScreenSize, sizeofthetargetdevice,
176x208 polish.ScreenWidth, e.g.ScreenSize.176x208or
polish.ScreenHeight ScreenSize.128x128
Symbols(example):
polish.ScreenSize.176x208
polish.ScreenWidth.176
polish.ScreenHeight.208
CanvasSize WidthtimesheightofanMIDP LikeScreenSize
Canvas.
CameraResolution Resolutionofthecamera. Variables:
polish.CameraResolution,
polish.CameraWidth,
polish.CameraHeight
Symbols(example):
polish.CameraResolution.320x
200
polish.CameraWidth.320
polish.CameraHeight.200
JavaPlatform ThesupportedJavaplatform. Variable:polish.JavaPlatform midp1ormidp2
CurrentlyeitherMIDP/1.0or
Symbols:
MIDP/2.0.
polish.midp1or
polish.midp2

26
TheDeviceDatabase

Capability Explanation PreprocessingAccess Groups


JavaConfiguration ThesupportedJava Variable: cldc1.0orcldc1.1
configuration.Currentlyeither polish.JavaConfigiration
CLDC/1.0orCLDC/1.1.
Symbols:
polish.cldc1.0or
polish.cldc1.1
JavaPackage SupportedAPIs,e.g.nokiaui, Variables: Respectivelythenameof
mmapi polish.api, thesupportedAPI,e.g.
polish.JavaPackage nokiauiormmapi(one
groupforeachsupported
Symbols(example):
API).
polish.api.nokiaui
polish.api.mmapi Example:nokiaui,mmapi
JavaProtocol Supporteddataexchange Variable:
protocols.AllMIDP/1.0devices polish.JavaProtocol
supporttheHTTPprotocol.All
Symbols(example):
MIDP/2.0devicessupport
polish.JavaProtocol.serial
additionallytheHTTPS
polish.JavaProtocol.https
protocol.
HeapSize Themaximumheapsize,e.g. Variable:
500kbor1.2MB polish.HeapSize
MaxJarSize Themaximumsizeofthe Variable:
MIDletJARbundle,e.g.100 polish.MaxJarSize
kbor2MB
OS Theoperatingsystemofthe Variable:
device,e.g.SymbianOS6.1 polish.OS
VideoFormat Thesupportedvideoformatsof Variable: Onegroupforeach
thedevice,e.g.3GPP,MPEG polish.VideoFormat supportedvideoformat.
4
Symbols(examples): Example:
polish.video.3gpp 3gpp
polish.video.mpeg4 mpeg4
polish.VideoFormat.3gpp
polish.VideoFormat.mpeg4
SoundFormat Thesoundformatswhichare Variable: Onegroupforeach
supportedbythedevice,e.g. polish.SoundFormat supportedaudioformat.
midi,wav
Symbols(examples): Example:
polish.audio.midi midi
polish.audio.wav wav
polish.SoundFormat.midi
polish.SoundFormat.wav

27
TheBuildProcess

TheBuildProcess
Introduction
Thebuildprocesscreatesreadytodeploy,optimizedapplicationbundlesfromthesourcecode.
Theprocessiscontrolledbythebuild.xmlfile,whichissituatedattherootoftheproject.Thisfile
isastandardAntfilewhichisusedtocontroltheJ2MEPolishtask.Youcanfindashort
introductiontoAntintheappendixonpage191.TheJ2MEPolishtaskisseparatedintothe
sectionsinfo,deviceRequirementsandbuild.Duringthebuildfollowingstepsare

}
accomplished:
Selectionofthesupporteddevices
Assemblingoftheresources
Preprocessingofthesourcecode,optimizingforthedevice
Compilationoftheapplication foreachselected
Obfuscationandshrinkingofthecompiledcode device

Preverification
CreationoftheJARandJADfiles

DefinitionoftheJ2MEPolishtask
YouneedtodefinetheJ2MEPolishtaskinthebuild.xmlfile:
<taskdef name="j2mepolish" classname="de.enough.polish.ant.PolishTask"
classpath="import/enough-j2mepolish-
build.jar:import/jdom.jar:import/proguard.jar"/>

Nowyoucanusethe2MEPolishTaskunderthenamej2mepolish.
YouneedalsodefinewheretofindtheWirelessToolkitbydefiningtheAntpropertywtk.home:
<property name="wtk.home" value="C:\WTK2.1" />

OnasystemwithouttheWirelessToolkit(likeMacOSX)youcanstilluseJ2MEPolishby
definingthepreverifyattributeofthe<build>elementinsteadofusingthewkt.homeproperty.

Example
Thefollowingexampleshowsacompletebuild.xmlfile:
<!-- This file controls the build process. -->
<!-- The most important target is the j2mepolish-target, -->
<!-- which controls for what devices the application should -->
<!-- be created and so on. -->
<!-- -->
<!-- Important: when you have no Wireless Toolkit installed -->
<!-- you need to define the "preverify"-attribute -->
<!-- of the <build>-element of the J2ME Polish task. -->
<!-- -->
<!-- When you call Ant from the command-line, you can -->
<!-- call "ant test j2mepolish" to skip the obfuscation -->

28
TheBuildProcess

<!-- and to build the example for fewer handsets. -->


<!-- The default target builds and obfuscates the example. -->
<!-- -->
<!-- The full documentation can be found at -->
<!-- http://www.j2mepolish.org -->
<!-- -->
<!-- Have fun! -->
<project
name="enough-j2mepolish-example"
default="j2mepolish">

<!-- The wtk.home property should point to the directory -->


<!-- containing the Wireless Toolkit. -->
<property name="wtk.home" value="C:\WTK2.1" />

<!-- Definition of the J2ME Polish task: -->


<taskdef name="j2mepolish" classname="de.enough.polish.ant.PolishTask"
classpath="import/enough-j2mepolish-
build.jar:import/jdom.jar:import/proguard.jar:import/retroguard.jar"/>

<!-- build targets, each target can be called via "ant [name]",
e.g. "ant clean", "ant notest j2mepolish" or just "ant" for
calling the default-target -->
<target name="test" >
<property name="test" value="true" />
</target>

<target name="init">
<property name="test" value="false" />
</target>

<!-- In this target the J2ME Polish task is used. -->


<!-- It has 3 sections: -->
<!-- 1. The info-section defines some general information -->
<!-- 2. The deviceRequirements-section chooses the devices -->
<!-- for which the application is optimized. -->
<!-- 3. The build-section controls the actual build -->
<!-- process. -->
<target name="j2mepolish"
depends="init"
description="This is the controller for the J2ME build process."
>
<j2mepolish>
<!-- general settings -->
<info
license="GPL"
name="J2ME Polish"
version="1.3.4"
description="A sample project"
vendorName="Enough Software"
infoUrl="http://www.j2mepolish.org"
icon="icon.png"
jarName="${polish.vendor}-${polish.name}-example.jar"
jarUrl="${polish.jarName}"
copyright="Copyright 2004 Enough Software. All rights reserved."
deleteConfirm="Do you really want to kill me?"
/>
<!-- selection of supported devices -->

29
TheBuildProcess

<!-- In the test mode the application is build only for the -->
<!-- Nokia/3650 and the 6600 phones, otherwise -->
<!-- the second deviceRequirements will be used instead. -->
<deviceRequirements if="test">
<requirement name="Identifier" value="Nokia/3650, Nokia/6600"
/>
</deviceRequirements>
<deviceRequirements unless="test">
<requirement name="Identifier" value="Nokia/Series60,
Nokia/Series60Midp2, Generic/midp2, Generic/midp1" />
<!-- on could use other devices for real builds, e.g. :
<or>
<and>
<requirement name="JavaPackage" value="nokia-ui"
/>
<requirement name="BitsPerPixel" value="16+" />
</and>
</or>
-->
</deviceRequirements>
<!-- build settings -->
<build
symbols="ExampleSymbol, AnotherExample"
imageLoadStrategy="foreground"
fullscreen="menu"
usePolishGui="true"
resDir="resources"
>
<!-- midlets definition -->
<midlet class="de.enough.polish.example.MenuMidlet" name="Example"
/>
<!-- project-wide variables - used for preprocessing -->
<variables>
<variable name="update-url"
value="http://www.enough.de/update" />
<variable name="title" value="J2ME Polish" />
</variables>
<!-- obfuscator: don't obfuscate when the test-property is true --
>
<obfuscator unless="test" name="ProGuard" />
<!-- debug settings: only include debug setting when the test-
property is true -->
<debug if="test" showLogOnError="true" verbose="true"
level="error">
<filter pattern="de.enough.polish.example.*" level="debug" />
<filter pattern="de.enough.polish.ui.*" level="warn" />
</debug>
<!-- user defined JAD attributes can also be used: -->
<jad>
<attribute name="Nokia-MIDlet-Category" value="Game"
if="polish.group.Series40" />
</jad>
</build>
</j2mepolish>
</target>

<target name="clean"
description="allows a clean build. You should call [ant clean] whenever

30
TheBuildProcess

you made changes to devices.xml, vendors.xml or groups.xml">


<delete dir="build" />
<delete dir="dist" />
</target>
</project>

InthefirstsectiontheJ2MEPolishtaskandthelocationofthewirelesstoolkitaredefined,
followedbythebuildtargetstest,init,j2mepolishandclean.Thetargetstestandinit
areresponsibleforenteringthetestmode.
IfyoucallAntwithoutanyarguments,theAntpropertytestwillbesettofalseintheinit
target.IfyoucallAntwiththeargumentstestj2mepolish,thetestpropertywillbesettotrue.
Thisallowscontrollingthebuildscriptwithoutchangingit.Intheexampletheobfuscationstepis
skippedwhenthetestpropertyistrue.Alsothedebugmessagesareonlyincludedwhentestistrue.
Youcanforceacompleterebuildbycallingantclean.Thiscanbenecessaryafteryoumade
changesinthedevicedatabaseorinrarecaseswhenthereisacompileerrorintheJ2MEPolish
packages.

The<info>Section
Inthe<info>sectiongeneralinformationabouttheprojectisdefined.
<info
license="GPL"
name="SimpleMenu"
version="1.3.4"
description="A test project"
vendorName="Enough Software"
infoUrl="http://www.enough.de/dictionary"
icon="icon.png"
jarName="${polish.vendor}-${polish.name}-${polish.locale}-example.jar"
jarUrl="${polish.jarName}"
copyright="Copyright 2004 Enough Software. All rights reserved."
deleteConfirm="Do you really want to kill me?"
/>
TheinformationgivinghereisusedforsettingtheJADandMANIFESTattributes.Ifyouneedto
setattributewhicharenotsupportedbythe<info>section,youcanalwaysusethe<jad>element,
whichisasubelementofthe<build>section.The<info>elementsupportsfollowingattributes:

<info> Required Explanation


Attribute
license Yes Thelicenseforthisproject.EitherGPLwhenthesourcecodeofthe
applicationispublishedundertheGNUGeneralPublicLicense,orthe
commerciallicensekey,whichcanbeobtainedatwww.j2mepolish.org.
name Yes Thenameoftheproject,thevariableMIDletNameoverridesthis
setting.Thisvariablecanbeusedtolocalizetheapplication.
version Yes Theversionoftheprojectintheformat[major].[minor].[build].
Example:version=2.1.10.ThevariableMIDletVersion
overridesthissetting.

31
TheBuildProcess

<info> Required Explanation


Attribute
description No Thedescriptionoftheproject.Abriefexplanationaboutwhatthis
applicationdoesshouldbegivenhere.ThevariableMIDlet
Descriptionoverridesthevaluegivenhere,thisvanbeusedtolocalize
theapplication.
vendorName Yes Thenameofthevendorofthisapplication.ThevariableMIDlet
Vendoroverridesthissetting.
jarName Yes Thenameofthejarfileswhichwillbecreated.Apartfromtheusual
J2MEPolishvariables,thefollowingvariablesareespeciallyuseful:
${polish.vendor}:Thevendorofthedevice,e.g.Samsungor
Motorola
${polish.name}:Thenameofthedevice
${polish.identifier}:Vendoranddevicename,e.g.Nokia/6600
${polish.version}:Theversionoftheprojectasdefinedabove.
${polish.language}:ThetwoletterISOlanguagecode,e.g.enor
de.
${polish.country}:ThetwoletterISOcountrycode,e.g.USor
DE.Thiscanbeemptywhennocountryisdefinedinthecurrent
locale.
${polish.locale}:Thecurrentlocale,e.g.enorde_DE.

Example:jarName=Game-${polish.vendor}-${polish.name}-
${polish.locale}.jarresultsintoGameNokia6600en.jarforan
applicationwhichhasbeenoptimizedfortheNokia/6600andusesthe
Englishlocale.
jarUrl No TheURLfromwhichthejarfilecanbedownloaded.Thisiseitherthe
HTTPaddress,orjustthenameofthejarfile,whenitisloadedlocally.
WhennojarUrlisdefined,thejarNamedefinedaboveisused.Apart
fromthevariablesavailableforthejarNameattribute,youcanusethe
nameofthejarfileasdefinedabove:
jarUrl=http://www.enough.de/midlets/Game/${polish.vendor
}/${polish.name}/${polish.jarName}
infoUrl No TheURLcontainingmoreinformationabouttheapplication.The
variableMIDletInfoURLoverridesthissetting,thisvanbeusedto
localizetheapplication.
copyright No Copyrightnotice.
deleteConfirm No Thetextwhichispresentedtotheuserwhenhetriestodeletethe
application.ThevariableMIDletDeleteConfirmoverridesthis
setting,thisvanbeusedtolocalizetheapplication.
installNotify No AHTTPURL,whichshouldbecalledafterthesuccessfulinstallation
oftheapplication..Thiscanbeusefulfortrackinghowmany

32
TheBuildProcess

<info> Required Explanation


Attribute
applicationsareinstalled,forexample.Theusercanpreventtheinstall
notify,though.OnecanusethesamevariablesasforthejarUrl
attribute.ThevariableMIDletInstallNotifyoverridesthissetting.
deleteNotify No AHTTPURL,whichshouldbecalledaftertheapplicationhasbeen
deletedfromthedevice.SeetheexplanationofinstallNotify.The
variableMIDletDeleteNotifyoverridesthissetting.
dataSize No Theminimumspacewhichisneededonthedevice,e.g.
dataSize=120kb.ThevariableMIDletDataSizeoverridesthis
setting.
permissions No Thepermissionswhichareneededbythisapplication,e.g.
javax.microedition.io.Connector.http.ThevariableMIDlet
Permissionsoverridesthissetting.
optionalPermi No Thepermissionswhichareusefulforthisapplicationtowork.The
ssions variableMIDletPermissionsOptoverridesthissetting.
profile No NormallyJ2MEPolishisusingtheJavaPlatformcapabilityofthe
currenttargetdevicefordeterminingthecorrect"MicroEditionProfile"
setting.Youcanoverridethisbyhardcodingtheprofileforalltarget
devices.Thisisusefulonlyincases,whenyoudeterminedevice
capabilitiesduringtheruntimeoftheapplicationandwanttodeliver
oneapplicationbundleforalltargetdevices.
configuration No NormallyJ2MEPolishisusingtheJavaConfigurationcapabilityofthe
currenttargetdevicefordeterminingthecorrect"MicroEdition
Configuration"setting.Youcanoverridethisbyhardcodingthe
configurationforalltargetdevices.Thisisusefulonlyincases,when
youdeterminedevicecapabilitiesduringtheruntimeoftheapplication
andwanttodeliveroneapplicationbundleforalltargetdevices.

The<deviceRequirements>Section
Theoptional<deviceRequirements>sectionisresponsibleforselectingthedeviceswhichare
supportedbytheapplication.Whenthissectionisomitted,theapplicationwillbeoptimizedforall
knowndevices.Anydevicecapabilitiesorfeaturescanbeusedforthedeviceselection:
<deviceRequirements if="test">
<requirement name="Identifier" value="Nokia/6600" />
</deviceRequirements>
<deviceRequirements unless="test">
<requirement name="JavaPackage" value="nokia-ui" />
<requirement name="BitsPerPixel" value="4+" />
</deviceRequirements>
Inthisexampletwoalternativedeviceselectionsaredefinedwhenthetestpropertyissettotrue

33
TheBuildProcess

(bydefiningitwith<property name="test" value="true" />),onlytheupper


<deviceRequirements>elementisusedandthesecond<deviceRequirements>elementisignored.
Theactualrequirementsaredefinedwiththesubelements<requirement>.Withoutany
clarification,alllistedrequirementsneedtobefulfilledbythedevicetobeselected.Thereare<or>,
<and>,<not>and<xor>elements,whichcanbeusedtodefinetherequirementsveryflexible.

deviceRequirements Required Explanation


Attribute
if No ThenameoftheAntpropertywhichneedstobetrueoryes
tousethis<deviceRequirements>.
unless No ThenameoftheAntpropertywhichneedstobefalseorno
tousethis<deviceRequirements>.

deviceRequirements Required Explanation


Element
requirement Yes Therequirementwhichneedstobefulfilledbythedevice
and No Seriesofrequirements,ofwhichallneedtobefulfilled.
or No Seriesofrequirements,ofwhichatleastoneneedstobefulfilled.
xor No Seriesofrequirements,ofwhichoneneedstobefulfilled.
not No Seriesofrequirements,ofwhichnonemustbefulfilled.

Theactualworkisdonebythe<requirement>element:
requirement Required Explanation
Attribute
name Yes Thenameoftheneededcapability,e.g.BitsPerPixel.
value Yes Theneededvalueofthecapability,e.g.4+foracolordepthor
atleast4bitsperpixel.
type No Theclasswhichcontrolsthisrequirement.Eitheraclasswhich
extendsthe
de.enough.polish.ant.requirements.Requirement class,or
oneofthebasetypesSize,Int,String,Versionor
Memory.Example:
<requirement name="MaxJarSize" value="100+ kb"
type="Memory" />

The<or>,<and>,<not>and<xor>elementscanbenestedinanymanner:
<deviceRequirements>
<requirement name="BitsPerPixel" value="4+" />
<or>
<requirement name="JavaPackage" value="nokia-ui, mmapi" />

34
TheBuildProcess

<and>
<requirement name="JavaPackage" value="mmapi" />
<requirement name="JavaPlatform" value="MIDP/2.0+" />
</and>
</or>
</deviceRequirements>
Inthisexampleeachsupporteddevicemusthaveacolordepthofatleast4bitsperpixel.
AdditionallythedeviceneedstosupporteithertheNokiaUIAPIandtheMobileMediaAPI
(mmapi),ortheMobileMediaAPIandtheMIDP/2.0platform.
Insteadofusingsuchnestedrequirements,youcanalsousethe"Term"requirementthatallowsyou
toselectdeviceswiththesamepowerlikethe#ifpreprocessingdirective.Thefollowingexample
includestheverysamerequirementsliketheaboveonebutonlyone"Term"requirementisused:
<deviceRequirements>
<requirement name="Term"
value="(polish.BitsPerPixel >= 4) and ((polish.api.nokia-ui and
polish.api.mmapi) or (polish.api.mmapi and polish.midp2))" />
</deviceRequirements>

J2MEPolishprovidesseveralrequirementsthatcanbeused"outofthebox":
requirementname Explanation
BitsPerPixel Neededcolordepthofthedevice:1ismonochrome,
4are16colors,
8=256colors,
16=65.536colors,
24=16.777.216colors.Example:
4+foratleast4bitsperpixelor16forprecisely16bitsperpixel.
<requirement name="BitsPerPixel" value="4+" />
ScreenSize Requiredwidthandheightofthedisplay,e.g.120+x100+fora
resolutionofatleast120pixelshorizontallyand100pixelsvertically.
<requirement name="ScreenSize" value="120+ x 100+" />
ScreenWidth Theneededhorizontalresolutionofthedisplay,e.g.120+foratleast120
pixels.
<requirement name="ScreenWidth" value="120+" />
ScreenHeight Theneededverticalresolutionofthedisplay,e.g.100+foratleast100
pixels.
<requirement name="ScreenHeight" value="100+" />
CanvasSize RequiredwidthandheightoftheMIDPCanvas.Somedevicesdonotallow
theusageofthecompletescreen.
<requirement name="CanvasSize" value="120+ x 100+" />
JavaPlatform Theneededplatform,e.g.MIDP/1.0orMIDP/2.0+.
<requirement name="JavaPlatform" value="MIDP/2.0+" />
JavaConfiguration Theneededconfiguration,e.g.CLDC/1.1+.
<requirement name="JavaConfiguration=" value="CLDC/1.1+" />
JavaPackage NeededAPIs,e.g.nokiaui,mmapi:
<requirement name="JavaPackage" value="nokia-ui, mmapi" />

35
TheBuildProcess

requirementname Explanation
JavaProtocol Neededdataexchangeprotocols,e.g.serial,socket:
<requirement name="JavaProtocol" value="serial,socket" />
HeapSize Theneededheapsizeofthedevice,e.g.200+kbor1.1+MB
<requirement name="HeapSize" value="200+kb" />
Vendor Thevendorofthedevice,e.g.NokiaorSiemens.
<requirement name="Vendor" value="Nokia, SonyEricsson" />
Identifier Theidentifierofthedevice,e.g.Nokia/6600.
<requirement name="Identifier" value="Nokia/6600,
SonyEricsson/P900" />
Feature Afeaturewhichneedstobesupportedbythedevice.
<requirement name="Feature" value="hasPointerEvents" />
Term Apreprocessingtermthatneedstobefulfilledbythedevice.Youcanuse
thisflexiblerequirementjustlikethe//#ifpreprocessingdirectiveinyour
sourcecode.
<requirement name="Term"
value="polish.mmapi && !polish.isVirtual && (polish.Vendor !=
Nokia)" />

The<build>Section
Withthe<build>sectiontheactualbuildprocessiscontrolled:
<build
symbols="showSplash, AnotherExampleSymbol"
fullscreen="menu"
usePolishGui="true"
>
<!-- midlets definition -->
<midlet class="MenuMidlet" name="Example" />
<!-- project-wide variables - used for preprocessing -->
<variables>
<variable name="update-url"
value="http://www.enough.de/update" />
</variables>
<!-- obfuscator settings: do not obfuscate when test is true -->
<obfuscator name="ProGuard" useDefaultPackage="true" unless="test" />
<!-- debug settings: only debug when test is true -->
<debug if="test"
visual="false" verbose="true" level="error">
<filter pattern="de.enough.polish.dict.*" level="debug" />
<filter pattern="de.enough.polish.ui.*" level="warn" />
</debug>
</build>

AttributesofthebuildSection

Thebuildsectionhasfollowingattributes:

36
TheBuildProcess

buildAttribute Required Explanation


sourceDir No Thepathtothesourcedirectory.Thedefaultpathiseither
source/src,sourceorsrc.Youcandefineseveralpathsby
separatingthemwithacolon':'orasemicolon';':
[path1]:[path2].Youcanalsoincludesourcedirectoriesbasedon
conditionswhenthenested<sources>elementisusedinstead
(seebelow).
binaryLibrariesor No Eitherthenameofthedirectorywhichcontainsbinaryonly
binaryLibrary librariesorthename(s)ofthelibraries.Severallibrariescanbe
separatedbycolons':'orbysemicolons';'.Whennopathis
defined,thelibrarieswillbesearchedwithintheimportfolder
bydefault.Thismechanismcanonlybeusedforthirdparty
APIs,whicharenotavailableonthephoneitself.DeviceAPIs
areautomaticallyincluded,aftertheyhavebeendefinedinthe
${j2mepolish.home}/apis.xmlfile.Pleasecomparethehow
toaboutincludingAPIsonpage181.
symbols No Projectspecificsymbols,e.g.showSplashwhichcanbe
checkedwith//#ifdefshowSplashinthesourcecode.Several
symbolsneedtobeseparatedbycomma.
usePolishGui No DefineswhethertheJ2MEPolishGUIshouldbeusedatall.
Possiblevaluesaretrue/yes,false/nooralways.When
trueisgiventheGUIwillbeusedonlyfordeviceswhichhave
therecommendedcapabilities(e.g.acolordepthofatleast8
bits).Whenalwaysisgiven,theGUIwillbeusedforall
devices.Defaultvalueistrue.
fullscreen No Defineswhetherthecompletescreenshouldbeusedfordevices
whichsupportafullscreenmode.Currentlytheseincludesall
MIDP/2.0devicesaswellasdevices,whichsupporttheNokia
UIAPI.Possiblevaluesareeitherno,yesandmenu.With
yesthecompletescreenisusedbutnocommandsare
supported.Withmenucommandscanbeusedaswell.Default
settingisno.Rememberthatyouneedtotargetaspecific
devicethathasknownSoftkeysforthisoption.Otherwisealways
thedefault(unpolishable)commandsmenuisused.
Alternativelythepreprocessingvariablepolish.FullScreencan
beset.Thisallowsafinergrainedcontrol,sincevariablescan
haveconditions.RefertotheGUIchapteronpage93formore
details.
imageLoadStrategy No Thestrategyforloadingpictures.Possiblevaluesareeither
foregroundorbackground.Theforegroundstrategyloads
imagesdirectlywhentheyarerequested.Thebackground
strategyloadstheimagesinabackgroundthread.Withthe

37
TheBuildProcess

buildAttribute Required Explanation


backgroundstrategythefeltperformanceofanapplicationcan
beincreased,butnotallpicturesmightbeshownrightaway
whentheuserentersascreen.Thedefinitionofthe
imageLoadStrategymakesonlysensewhentheJ2MEPolish
GUIisused(usePolishGui=true).Defaultstrategyis
foreground.Whentheforegroundstrategyisused,the
preprocessingsymbolpolish.images.directLoadwillbe
defined.Whenusingthebackgroundstrategy,thesymbol
polish.images.backgroundLoadisdefined.
javacTarget No Thetargetforthejavacompiler.Bydefaultthe1.2targetis
used,unlessaWTK1.xorMacOSXisused,inwhichcasethe
target1.1isused.
preverify No ThepathtothepreverifyexecutableoftheWirelessToolkit.The
programisusuallywithinthebinfolderoftheWireless
Toolkit.Thiscanbeusedfordefiningapreverfyingprogram
differentfromthestandardWTKprogram.
polishDir No ThedirectorycontainingthesourcesofJ2MEPolish.Thisis
usedbydevelopersoftheJ2MEPolishGUIitself.
devices No Pathtothedevices.xmlfile.Defaultstodevices.xmlinthe
currentfolderorinenoughj2mepolishbuild.jar.
groups No Pathtothegroups.xmlfile.Defaultstogroups.xmlinthecurrent
folderorinenoughj2mepolishbuild.jar.
vendors No Pathtothevendors.xmlfile.Defaultstovendors.xmlinthe
currentfolderorinenoughj2mepolishbuild.jar.
apis No Pathtotheapis.xmlfile.Defaultstoapis.xmlinthecurrent
folderorinenoughj2mepolishbuild.jar.
midp1Path No PathtotheMIDP/1.0API.Defaultstoimport/midp1.jar.
midp2Path No PathtotheMIDP/2.0API.Defaultstoimport/midp2.jar.
workDir No Thetemporarybuildfolder.Defaultstobuild.
destDir No Thefolderintowhichthereadytodeployapplicationbundles
shouldbestored.Defaultstodist.
apiDir No ThefolderinwhichtheAPIsarestored,defaultstoimport.
resDir No Thefolderwhichcontainsalldesigndefinitionsandother
resourceslikeimages,moviesetc.Bysettingadifferentfolder,
completelydifferentdesignscanbedemonstrated.Defaultfolder
isresources.Youcanalsousethe<resources>subelement
whichallowstofinetunetheresourceassemblingprocessas
well.

38
TheBuildProcess

buildAttribute Required Explanation


obfuscate No Eithertrueorfalse.Defineswhethertheapplicationsshould
beobfuscated.Defaultstofalse.Alternativelythenested
elementobfuscatorcanbeused(seebelow).
obfuscator No Thenameoftheobfuscator.DefaultstoProGuard.Possible
valuesareProGuard,KlassMaster,Dasho,YGuardor
RetroGuard.Alternativelythenestedelementobfuscatorcan
beused(seebelow).
compilerMode No Whenthecompilermodeisactivated,J2MEPolishwillnot
packagetheapplicationandonlyprocessonedevice.Thismode
isusefulforIDEswhichsupportindirectcompilationlike
NetBeansforexample.YoucanselectRuninNetBeansand
NetBeansusesJ2MEPolishascompiler,packagesthe
applicationandstartstheemulatorthissavesvaluabletime
duringthedevelopmentphase.Possiblevaluesaretrueor
false.Thecompilermodeisdeactivated(false)bydefault.
compilerDestDir No ThecompilerDestDirattributedefineswherethecompiled
(andobfuscated)classesshouldbestored.Thedefaulttarget
directoryisbin/classes.
compilerModePrever No DefineswhetherJ2MEPolishshouldpreverifythecompiled
ify classesaswell.ThisisneededforusingJ2MEPolishasa
compilerfortheEclipseMEplugin.Possiblevaluesaretrueor
false.Thepreverifyingisdeactivated(false)bydefault.
encoding No TheencodingforthegeneratedJADandMANIFESTfiles,this
defaultsto"UTF8"likethestandardmandates.

ElementsofthebuildSection
Thebuildsectionsupportsseveralnestedelements:<sources>,<midlet>,<midlets>,<resources>,
<obfuscator>,<variables>,<debug>,<jad>,<manifestFilter>,<preprocessor>and<java>.

<sources>
The<sources>elementcanbeusedforafinergrainedcontrolofthesourcedirectories.Thiscanbe
usefultoincludetestclasses,forexample:
<sources>
<source dir="source/src" />
<source dir="source/test" if="test" />
</sources>

sourcesAttribute Required Explanation


if No TheAntpropertywhichneedstobetrueforthenestedsource
directoriestobeused.

39
TheBuildProcess

sourcesAttribute Required Explanation


unless No TheAntpropertywhichneedstobefalseforthenestedsource
directoriestobeused.

sourceAttribute Required Explanation


dir Yes ThedirectorycontainingJavasourcefiles.
if No TheAntpropertywhichneedstobetrueforthissource
directorytobeused.
unless No TheAntpropertywhichneedstobefalseforthissource
directorytobeused.

<midlet>and<midlets>
The<midlet>elementdefinestheactualMIDletclass:
<midlet class="de.enough.polish.example.ExampleMidlet" />

midletAttribute Required Explanation


class Yes ThecompletepackageandclassnameoftheMIDlet.
name No ThenameoftheMIDlet.Defaultistheclassnamewithoutthe
package:TheMIDletcom.company.SomeMidletisnamed
SomeMidletbydefault.
icon No TheiconofthisMIDlet.Whennoneisdefined,theicondefined
inthe<info>sectionwillbeused.
number No ThenumberofthisMIDlet.ThisisinterestingonlyforMIDlet
suitesinwhichseveralMIDletsarecontained.
if No TheAntpropertyorpreprocessingdirectivewhichneedstobe
trueforthisMIDlettobeincluded.
unless No TheAntpropertyorpreprocessingdirectivewhichneedstobe
falseforthisMIDlettobeincluded.
Theoptional<midlets>elementisusedasacontainerforseveral<midlet>elements:
<midlets>
<midlet class="de.enough.polish.example.ExampleMidlet" />
<midlet name="J2ME Polish Demo" number="2" icon="no2.png"
class="de.enough.polish.example.GuiDemoMidlet" />
</midlets>

<iappli>
The<iappli>or<doja>elementdefinestheIApplicationclassofyourDoJarelease.Thisisonly
applicablewhenyouaretargetingthisplatform(seepage178).

iappli Require
Explanation
Attribute d

40
TheBuildProcess

class Yes ThecompletepackageandclassnameofthemainIApplication.


TheAntpropertyorpreprocessingdirectivethatneedstobe/result"true"
if No
forthisiapplitobeused.
TheAntpropertyorpreprocessingdirectivethatneedstobe/result
unless No
"false"forthisiapplitobeused.

<resources>
<resources
dir="resources"
excludes="*.txt"
>
<fileset
dir="resources/multimedia"
includes="*.mp3"
if="polish.audio.mp3"
/>
<fileset
dir="resources/multimedia"
includes="*.mid"
if="polish.audio.midi and not polish.audio.mp3"
/>
<fileset
dir="resources/multimedia/images/${polish.language}"
includes="*.png"
/>
<localization locales="de, en" unless="test" />
<localization locales="en" if="test" />
</resources>

The<resources>elementcanbeusedtofinetunetheresourcesassemblingaswellasthe
localizationoftheapplication.Whenitisused,theresDirattributeofthe<build>sectionshould
notbeused.The<resources>elementsupportsfollowingattributes:

resourcesAttribute Required Explanation


dir No Thedirectorycontainingallresources,defaultstothe
resourcesfolder.
defaultexcludes No Eitheryes/trueorno/false.Defineswhethertypical
filesshouldnotbecopiedintheapplicationjarbundleduring
packaging.Thefilespolish.css,Thumbs.db,anybackup
files(*.bakand*~)andthemessagesfilesusedinthe
localizationareexcludedbydefault.
excludes No AdditionalfileswhichshouldnotbeincludedintheJARfiles
canbedefinedusingtheexcludesattribute.Severalfilesneed
tobeseparatedbycomma.Thestarcanbeusedtoselectseveral
filesatonce,e.g.*.txt,readme*.

41
TheBuildProcess

resourcesAttribute Required Explanation


locales No Thelocaleswhichshouldbesupportedinacommaseparated
list.Alternativelythenested<localization>elementcanbeused.
ThestandardJavalocaleabbreviationsareused,e.g.defor
German,enforEnglishandfr_CAforCanadianFrench.
filterZeroLengthFiles No Defineswhetherfileswithalengthof0shouldalsobefiltered.
Thisistruebydefault,soanyfileswithalengthof0byteswill
notbecopied,unlessyouactivatethisbysetting
filterNullFiles="false".Youcanusethismechanismfor
removingfilesforspecificdevicesordevicegroups.Imaginethe
situationwhereyouhaveaimagefileintheresourcesdirectory.
Youwanttousethatimageonalldevicesexceptthe
Vendor/DeviceNameone.Youcannowremovethatfileforthat
specificdevicesbyplacingafilewiththesamenamebutwitha
lengthof0bytesintoresources/Vendor/DeviceName.

The<resources>elementsacceptsthenestedelements<filter>,<fileset>,<localization>and
<copier>:

The<filter>Subelement

Sometimesitiseasiertoexcluderesourcesforspecificdevicesratherthantoincludeitfortheother
devices.Youcanuseanynumberof<filter>elementsforthispurpose.Thefollowingelement
removesall*.midfileswhenthetargetdevicesupportsbothMIDIaswellasAMRfiles:
<filterexcludes="*.mid"if="polish.audio.midiandpolish.audio.amr"/>

filterAttribute Required Explanation


excludes Yes Defineswhichfilesshouldbeexcluded,e.g.*.mid.Youcan
alsouseregularexpressionsinthisattribute.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttrueforthisfiltertobeused.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalseforthisfiltertobeused.

The<fileset>Subelement

The<fileset>behaveslikeanyAntfileset,butitofferstheadditionalifandunlessattributesfor
allowingafinegrainedcontrol.Themostimportantattributesare:
filesetAttribute Required Explanation
dir Yes Thebasedirectoryofthisfileset.Thisdirectoryneedstoexist
unlessyouusevariablesinitlike${polish.vendor},
${polish.name},${polish.language},${polish.country}

42
TheBuildProcess

filesetAttribute Required Explanation


andsoon.YoucanuseanyJ2MEPolishpreprocessingvariable
orAntpropertyinthedirattribute.
includes Yes Defineswhichfilesshouldbeincluded,e.g.*.mid.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttrueforthisfilesettobeincluded.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalseforthisfilesettobeincluded.

The<localization>Subelement

Withthe<localization>elementtheinternationalizationoftheapplicationcanbecontrolled.It
supportsfollowingattributes:

localization Required Explanation


Attribute
locales Yes Thelocaleswhichshouldbesupportedinacommaseparated
list.ThestandardJavalocaleabbreviationsareused,e.g.de
forGerman,enforEnglishandfr_CAforCanadianFrench.
messages No Thefilewhichcontainsthetranslations.Thisdefaultsto
messages.txt.
dynamic No Defineswhetherdynamictranslationsshouldbeenabled.
Dynamictranslationscanbechangedduringruntimebutrequire
additionalresources.Thisdefaultsto"false".
default No Thedefaultlocalizationthismakesonlysensewhendynamic
translationsareenabled.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttrueforthislocalizationtobeused.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalseforthislocalizationtobeused.

Moreinformationaboutlocalizationcanbefoundinthelocalizationchapteronpage70.

The<copier>Subelement

Usethe<copier>elementtotransformtheresourcesbeforetheyarepackagedinthefinalJARfile.
Youcanchainseveralcopierstogetherjustbydefiningseveral<copier>elements.
copierAttribute Required Explanation
name Yes, Thenameoftheresourcecopier,e.g.antcall,renameror
unless svgconverter.Youcanregisteryourownresourcecopierin

43
TheBuildProcess

copierAttribute Required Explanation


classis ${polish.home}/customextensionswiththetype
set resourcecopier.
class No Theclassthatextendsthe
de.enough.polish.resources.ResourceCopierclass.
classpath No Theclasspaththatisused.
target No Thetargetinyourbuild.xmlscriptthatshouldbecalledwhen
usingtheantcallcopier.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttrueforthiscopiertobeused.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalseforthiscopiertobeused.

The antcall Resource Copier


Theantcallresourcecopierexecutesanothertargetinyourbuild.xmlscriptforcopyingthe
resources.Youcanuseall(lowercase)J2MEPolishvariablesandpropertiesofthecurrenttarget
deviceaswellasfollowingspecificproperties:
${polish.resources.target}:containsthetargetdirectory,towhichtheresourcesneedtobe
copied
${polish.resources.files}:includesacommaseparatedlistofthefilesthatshouldbecopied
${polish.resources.filePaths}:includesasemicolon(Windows)orcolon(Unix)separatedlistof
thefilesthatshouldbecopied.
Youcanalsospecifyyourownpropertiesbyusingnested<parameter>elements.
<copier name="antcall" target="copyresources">
<parameter name="MySettings" value="${polish.name}.settings" />
</copier>

The renamer Resource Copier


Usetherenamerresourcecopierformodifyingthefilenamesoftheresourcesbeforetheyare
packagedinthefinalJAR.Thefollowingrenamerremovesallcharactersthataresurroundedby
curlybraces.Youcanusethisforgivingyourresourcesmeaningfulnameswhileusingshortnames
intheJARfile.Thefilei0{startgameicon}.pngwillberenamedtoi0.png,forexample.Thissaves
somepreciousspace.
<copier name="renamer">
<!-- use a regular expression for defining
name parts that should be changed:
-->
<parameter name="searchPattern" value="\{.*\}" />
<!-- define the replacement for the searchPattern here: -->
<parameter name="replacement" value="" />
</copier>

44
TheBuildProcess

The svgconverter Resource Copier


UsethesvgconverterformodifyingSVGimagesoftheresourcesbeforetheyarepackagedinthe
finalJAR.Thesvgconverterallowsyoutoprovideonlyoneiconorbackgroundimageforavariety
ofphones.ItscalestheSVGimagetotheappropriatesizeofthecurrenttargetdeviceandconverts
itintoaPNGimage.Foranbackgroundimageyouhavetostartnamingyourimage
bg(bg+whatever+.svg),foraniconstartwithicon.Thesvgconverterthenusesthedefined
ScreenSizeandIconSizeofthetargetdeviceforscalingsuchimages.Whenthetargetdevice
doesnotspecifythesesizesthedefaultsizeforiconsis15x15andforbackgrounds128x160pixels.
<copier name="svgconverter" />

<compiler>
Theoptional<compiler>elementcanbeusedforspecifyinganycompilerarguments.J2MEPolish
normallycallstheJavacompilernormallywiththeappropriateclasspathaswellasbootclasspath
forthecurrenttargetdevice.Insomecasesyoumightwanttoadjustthecompilersettings,however,
soyoucanusethenested<compiler>element.Alongtoallattributesofthestandard<javac>task,
the<compiler>elementalsosupportsthe"if"and"unless"attributesforselectingtoappropriate
compilersetting:

compilerAttribute Required Explanation


srcdir No Locationofthejavafiles,whichdefaultstothetemporary
directorytowhichthepreprocessedfilesarewritten.
destdir No Locationtostoretheclassfiles.Thisdefaultstothetemporary
builddirectoryintowhichclassfilesarewrittenbeforetheyare
obfuscated.
includes No Commaorspaceseparatedlistoffiles(maybespecifiedusing
wildcardpatterns)thatmustbeincluded;all.javafilesare
includedwhenomitted.
includesfile No Thenameofafilethatcontainsalistoffilestoinclude(maybe
specifiedusingwildcardpatterns).
excludes No Commaorspaceseparatedlistoffiles(maybespecifiedusing
wildcardpatterns)thatmustbeexcluded;nofiles(exceptdefault
excludes)areexcludedwhenomitted.
excludesfile No Thenameofafilethatcontainsalistoffilestoexclude(maybe
specifiedusingwildcardpatterns).
classpath No Theclasspathtouse.J2MEPolishincludesallsupported
librariesofthecurrenttargetdevicebydefault.
classpathref No Theclasspathtouse,givenasareferencetoapathdefined
elsewhere.
sourcepath No Thesourcepathtouse;defaultstothevalueofthesrcdir
attribute.Tosuppressthesourcepathswitch,usesourcepath="".

45
TheBuildProcess

compilerAttribute Required Explanation


sourcepathref No Thesourcepathtouse,givenasareferencetoapathdefined
elsewhere.
bootclasspath No Locationofbootstrapclassfiles.J2MEPolishuseseitherthe
platformspecificlibraryfilesforthebootclasspath,e.g.
midp1.jarormidp2cldc11.jar.
bootclasspathref No Locationofbootstrapclassfiles,givenasareferencetoapath
definedelsewhere.
extdirs No Locationofinstalledextensions.
encoding No Encodingofsourcefiles.(Note:gcjdoesn'tsupportthisoption
yet.)
nowarn No Indicateswhetherthenowarnswitchshouldbepassedtothe
compiler;defaultstooff.
debug No Indicateswhethersourceshouldbecompiledwithdebug
information;defaultstooff.Ifsettooff,g:nonewillbepassed
onthecommandlineforcompilersthatsupportit(forother
compilers,nocommandlineargumentwillbeused).Ifsetto
true,thevalueofthedebuglevelattributedeterminesthe
commandlineargument.J2MEPolishonlyenablesthe
debuggingwhenthe<debug>elementisactiveforthecurrent
targetdevice.
debuglevel No Keywordlisttobeappendedtothegcommandlineswitch.
Thiswillbeignoredbyallimplementationsexceptmodernand
classic(ver>=1.2).Legalvaluesarenoneoracommaseparated
listofthefollowingkeywords:lines,vars,andsource.If
debuglevelisnotspecified,bydefault,nothingwillbeappended
tog.Ifdebugisnotturnedon,thisattributewillbeignored.
optimize No Indicateswhethersourceshouldbecompiledwithoptimization;
defaultstooff.
deprecation No Indicateswhethersourceshouldbecompiledwithdeprecation
information;defaultstooff.
target No GenerateclassfilesforspecificVMversion(e.g.,1.1or1.2).
J2MEPolishuses1.2bydefaultwhentheWTK2.xisused.The
targetcanalsobesetwiththe"javacTarget"attributeofthe
<build>element.
verbose No Asksthecompilerforverboseoutput;defaultstono.
depend No Enablesdependencytrackingforcompilersthatsupportthis
(jikesandclassic).
includeAntRuntime No WhethertoincludetheAntruntimelibrariesintheclasspath;
defaultstofalse.

46
TheBuildProcess

compilerAttribute Required Explanation


includeJavaRuntime No Whethertoincludethedefaultruntimelibrariesfromthe
executingVMintheclasspath;defaultstono.
fork No WhethertoexecutejavacusingtheJDKcompilerexternally;
defaultstono.
executable No Completepathtothejavacexecutabletouseincaseof
fork="yes".DefaultstothecompileroftheJavaversionthatis
currentlyrunningAnt.Ignorediffork="no".SinceAnt1.6this
attributecanalsobeusedtospecifythepathtotheexecutable
whenusingjikes,jvc,gcjorsj.
memoryInitialSize No TheinitialsizeofthememoryfortheunderlyingVM,ifjavacis
runexternally;ignoredotherwise.DefaultstothestandardVM
memorysetting.(Examples:83886080,81920k,or80m)
memoryMaximumSi No ThemaximumsizeofthememoryfortheunderlyingVM,if
ze javacisrunexternally;ignoredotherwise.Defaultstothe
standardVMmemorysetting.(Examples:83886080,81920k,or
80m)
failonerror No Indicateswhetherthebuildwillcontinueevenifthereare
compilationerrors;defaultstotrue.
source No Valueofthesourcecommandlineswitch;willbeignoredbyall
implementationspriortojavac1.4(ormodernwhenAntisnot
runningina1.3VM)andjikes.Ifyouusethisattributetogether
withjikes,youmustmakesurethatyourversionofjikes
supportsthesourceswitch.Legalvaluesare1.3,1.4and1.5
bydefault,the"1.3"sourceswitchwillbeused.
compiler No Thecompilerimplementationtouse.Ifthisattributeisnotset,
thevalueofthebuild.compilerproperty,ifset,willbeused.
Otherwise,thedefaultcompilerforthecurrentVMwillbeused.
listfiles No Indicateswhetherthesourcefilestobecompiledwillbelisted;
defaultstono.
tempdir No WhereAntshouldplacetemporaryfiles.Thisisonlyusedifthe
taskisforkedandthecommandlineargslengthexceeds4k.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttrueforthiscompilersettingtobeused.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalseforthiscompilersettingtobeused.

The<compilerargs>Subelement

Youcanspecifyadditionalcommandlineargumentsforthecompilerwithnested<compilerarg>

47
TheBuildProcess

elements.TheseelementsarespecifiedlikeCommandlineArgumentsbuthaveanadditional
attributethatcanbeusedtoenableargumentsonlyifagivencompilerimplementationwillbeused.

compilerargs Required Explanation


Attribute
value Eithervalue,line, Asinglecommandlineargument;cancontainspace
fileorpath characters.
line Eithervalue,line, Asinglecommandlineargument;cannotcontainspace
fileorpath characters.
file Eithervalue,line, Thenameofafileasasinglecommandlineargument;
fileorpath willbereplacedwiththeabsolutefilenameofthefile.
path Eithervalue,line, Astringthatwillbetreatedasapathlikestringasa
fileorpath singlecommandlineargument;youcanuse;or:as
pathseparatorsandAntwillconvertittotheplatform's
localconventions.
compiler No Onlypassthespecifiedargumentifthechosencompiler
implementationmatchesthevalueofthisattribute.

<obfuscator>
Theoptional<obfuscator>elementcontrolstheobfuscatingoftheapplicationbundle,which
decreasesthejarsizeandmakesitdifficulttoreverseengineertheapplication.
<obfuscator name="ProGuard" useDefaultPackage="true" unless="test" />

obfuscatorAttribute Required Explanation


name No Thenameoftheobfuscatorwhichshouldbeused.Defaultsto
ProGuard.PossiblevaluesareProGuard,KlassMaster,
Dasho,YGuardorRetroGuard.
useDefaultPackage No J2MEPolishcanmoveallclassestothedefaultpackageforyou.
ThisincludestheMIDletclassesaswellandcanresultina
smallerjarsize.Pleasenotethatyouareresponsiblefor
preventingnameclashesofclasses.Youdonotneedtoadjust
your<midlet>settings,thisisdoneautomaticallybyJ2ME
Polish.Youneed,however,adjustany<keep>settingsyouhave.
"useDefaultPackage"defaultstofalse.Whenthedefault
packageisused,thepreprocessingsymbol
"polish.useDefaultPackage"isdefined.Youcanusethistoadjust
theloadingofdynamicclasses.
if No ThenameoftheAntproperty,whichneedstobetrueoryes,
whenthis<obfuscator>elementshouldbeused.
unless No ThenameoftheAntproperty,whichneedstobefalseorno,

48
TheBuildProcess

obfuscatorAttribute Required Explanation


whenthis<obfuscator>elementshouldbeused.
class No Theclasswhichcontrolstheobfuscator.Eachclasswhich
extendsde.enough.polish.obfuscate.Obfuscator canbe
used.Withthismechanismthirdpartyobfuscatorscanbe
integratedeasily(comparepage157).
classPath No Theclasspathforthisobfuscator.Thisisusefulforintegratinga
thirdpartyobfuscator.

Anynumberof<obfuscator>elementscanbeusedinaproject.Allactiveobfuscatorsare
combinedbyJ2MEPolish.
The<obfuscator>supportsthesubelements<keep>and<parameter>.

The<keep>Subelement

The<keep>elementisusedtodefineclasseswhichareloadeddynamically(e.g.with
Class.forName(...))andshouldnotbeobfuscated:
<obfuscator unless="test" enable="true" name="ProGuard" >
<keep class="com.company.dynamic.SomeDynamicClass" />
<keep class="com.company.dynamic.AnotherDynamicClass" />
</obfuscator>

keepAttribute Required Explanation


class Yes Thefullnameoftheclasswhichshouldnotgetobfuscated.

TheusedMIDletclassesdonotneedtobesetwiththe<keep>element,sincetheyaresavedfrom
obfuscationautomatically.

The<parameter>Subelement

The<parameter>elementisusedtospecifyparametersfortheobfuscator.Thiscanbeusefulfor
integratingthirdpartyobfuscatorswhichrequireadditionalsettings(seepage157):
<obfuscator unless="test" enable="true" name="ProGuard" >
<keep class="com.company.dynamic.SomeDynamicClass" />
<keep class="com.company.dynamic.AnotherDynamicClass" />
<parameter name="scriptFile" value="../scripts/obfuscate.script" />
</obfuscator>

parameterAttribute Required Explanation


name Yes Thenameoftheparameter.
value Yes Thevalueoftheparameter.

49
TheBuildProcess

CombiningSeveralObfuscators

Severalobfuscatorscanbecombinedjustbyspecifyingseveral<obfuscator>elements.Whenthe
<keep>subelementisused,itonlyneedstobespecifiedonofthe<obfuscator>elements.
J2MEPolishwillthenusetheobfuscatedoutputofoneobfuscatorasinputforthefollowing
obfuscator.

SpecificObfuscatorSettings

ProGuard
ProGuardisanexcellentobfuscator,shrinkerandoptimizerbyEricLafortune.Itisfreelyavailabe
undertheGNUGeneralPublicLicenseandcanbedownloadedfrom
http://proguard.sourceforge.net.

IfyouwanttouseProGuardasanobfuscator,pleasemakesurethattheproguard.jarfileislistedin
theclasspathoftheJ2MEPolishtaskdefinition(build.xml):
<taskdef name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"
classpath="${polish.home}/import/enough-j2mepolish-
build.jar:${polish.home}/import/jdom.jar:${polish.home}/import/proguard.jar"/>

YoucanuseProGuardbysettingthenameattributeofthe<obfuscator>elementtoProGuard.
ProGuard3.xoffersanadditionaloptimizationofthebytecode,whichisdisabledbydefault.The
optimizationcanbeenabledbysettingtheoptimizeparametertotrue:
<obfuscator unless="test" enable="true" name="ProGuard" >
<parameter name="optimize" value="true" />
</obfuscator>

Atextfilewhichlistsallrenamingoperationsiswrittento
build/[vendor]/[device]/[locale]/obfuscation-map.txt.Thisfileisusefulifyouget
exceptionsintheobfuscatedapplication.

yGuard
TheyGuardobfuscatorbytheyWorksGmbHisanotherinterestingobfuscatorandcodeshrinker.
J2MEPolishincludesthelibraryclasses,whicharelicensedundertheGNULesserGeneralPublic
License.Thefullobfuscatorisfreelyavailablefromhttp://www.yworks.de.
IfyouwanttouseyGuardasanobfuscator,pleasemakesurethateithertheyguardlib.jarorthe
originalyguard.jarislistedintheclasspathoftheJ2MEPolishtaskdefinition(build.xml):
<taskdef name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"
classpath="${polish.home}/import/enough-j2mepolish-
build.jar:${polish.home}/import/jdom.jar:${polish.home}/import/yguard-lib.jar"/>

TheyGuardobfuscatorcanbeusedbysettingthenameattributeofthe<obfuscator>elementto
YGuard:
<obfuscator unless="test" enable="true" name="YGuard" />

50
TheBuildProcess

RetroGuard
RetroGuardisthebasisofbothyGuardandProGuardandwasdevelopedbyRetrologic
Systems/MarkWelsh.ItislicensedundertheGNULesserGeneralPublicLicenseandisincluded
inJ2MEPolishbydefault.Itcanbedownloadedfromhttp://www.retrologic.com.
YoucanuseRetroGuardjustbysettingthenameattributetoRetroGuard:
<obfuscator unless="test" enable="true" name="RetroGuard" />

Zelix KlassMaster
KlassMasterisacommercialobfuscatoravailablefromZelixPtyLtd.Afreeevaluationversioncan
berequestedathttp://www.zelix.com.
TheKlassMasterintegrationisbasedontheWTKmechanismforcallingobfuscators,therefore
boththeZKM.jaraswellasthekenv.zipneedstobeontheclasspath:
<taskdef name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"
classpath="${polish.home}/import/enough-j2mepolish-
build.jar:${polish.home}/import/jdom.jar:${polish.home}/import/ZKM.jar:${wtk.hom
e}/wtklib/kenv.zip"/>

TheKlassMasterintegrationallowsseveralparameterstobeset:
enableFlowObfuscation:theflowobfuscationincreasesthesecurityoftheapplication,butthe
applicationsizeaswell.Itisdeactivatedbydefault,therefore.Itcanbeactivatedbysettingthe
enableFlowObfuscationparametertotrue.

ObfuscateFlowLevel:Theobfuscationflowlevelcanalsobesetdirectly,e.g.noneor
aggressive.ThisparametertakesprecedentabovetheenableFlowObfuscationparameter.
ScriptFile:Thefilecontainingthefullscriptcanalsobeset.Inthatcasepleasenotethatthe
sourcejarfileisalwaysthebuild/source.jarandthetargetfileisthebuild/dest.jar.
ThefollowingexampleshowsapossibleinvocationofKlassMaster:
<obfuscator unless="test" enable="true" name="KlassMaster" >
<parameter name="ObfuscateFlowLevel" value="none" />
</obfuscator>

DashO Pro
DashOProisacommercialobfuscatorbyPreemptiveSolutions.Afreeevaluationversioncanbe
requestedathttp://www.preemptive.com.
WhentheDashOProobfuscatorisused,eithertheAntpropertydasho.homeortheparameter
DashoHomeneedstobegiven.Theclasspathdoesnotneedtobemodified.
TheDashOProobfuscatorsupportsfollowingparameters:
DashoHome:needstopointtotheinstallationdirectoryoftheDashOProobfuscator.

Version:needstocorrespondtotheusedversionofDashO.Thecurrentdefaultversionis3.1.

enableFlowObfuscation:whentrueisgiven,DashOwillobfuscatetheapplicationflowas
well.Thisisdeactivatedbydefault.

51
TheBuildProcess

enableStringEncription:whentrueisgiven,StringswillbeobfuscatedbyDashOaswell.
Sincethisdecreasestheperformance,itisdeactivatedbydefault.
enableRenaming:whentrueisgiven,allpossibleclasseswillberenamed.Thisisactivatedby
default.
enableOptimization:whentrueisgiven,thebytecodewillbeoptimizedbyDashO.This
featureisactivatedbydefault.
ConstantPoolTag:atagwhichwillbeaddedtoallprocessedclasses.Thisisonlyvisiblewhena
decompilerisused.
ScriptFile:Thefilecontainingthefullscriptcanalsobeset.Inthatcasepleasenotethatthe
sourcejarfileisalwaysthebuild/source.jarandthetargetfileisthebuild/dest.jar.
Areportabouttherenamedclasesaswellasmethodswillbewrittento
build/[vendor]/[device]/[locale]/obfuscation-map.txt.Thisfileisusefulforresolving
stacktracesintheobfuscatedapplication.
ThisexampleshowstheintegrationofDashOPro:
<obfuscator unless="test" enable="true" name="Dasho" >
<parameter name="DashoHome" value="/home/user/DashOPro_3.1" />
<parameter name="Version" value="3.1" />
</obfuscator>

JODE
JODEisquiteapowerfuloptimizer,shrinkerandobfuscatorbyJochenHoenicke.Itislicensed
undertheGNUGeneralPublicLicenseandisavailableathttp://jode.sourceforge.netfreeof
charge.
IfyouwanttouseJODE,pleasemakesurethatthejodejarfileisontheclasspath:
<taskdef name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"
classpath="${polish.home}/import/enough-j2mepolish-
build.jar:${polish.home}/import/jdom.jar:${polish.home}/import/Jode-1.1.2-
pre1.jar"/>

JODEsupportstheScriptFileparameterwhichcanbeusedtospecifytheobfuscatorscript.
Pleasenotethatthesourcejarfileisalwaysthebuild/source.jarandthetargetfileisthe
build/dest.jar:
<obfuscator unless="test" enable="true" name="Jode" >
<parameter name="ScriptFile" value="obfuscate.jos" />
</obfuscator>

Whennoscriptfileparameterispresent,J2MEPolishwillcreateadefaultscript.Dependingonthe
applicationandenvironment,severalproblemsrangingfrompreverification/linkingerrorsto
NullPointerExceptionsintheJODEAPIcanoccur.Maybesomeonewithmoreexperiencewith
JODEcanprovidehelpherepleasegetintouchwithj2mepolish@enough.de.

<variables>and<variable>
Theoptional<variables>elementcontainsseveralvariabledefinitions,whichcanbeusedforthe

52
TheBuildProcess

preprocessing.Thismechanismcanbeusedforexampletodefineconfigurationvalues:
<variables includeAntProperties="true">
<variable name="update-url" value="http://www.enough.de/update" />
<variable name="polish.TiledLayer.splitImage"
value="true"
if="polish.Vendor == Nokia" />
</variables>

variablesAttribute Required Explanation


includeAntProperties No Eithertrueorfalse.WhentrueallAntpropertieswillbe
includedandcanbeusedinthepreprocessing.Defaultsto
false.

The<variables>elementcontainsanarbitrarynumberof<variable>elements,whichdefinethe
actualvariables.Eachvariableneedstheattributesnameandvalue:
variableAttribute Required Explanation
name Yes Thenameofthevariable.
unless
fileis
used
value Yes Thevalueofthevariable.
unless
fileis
used
file No Thefilewhichcontainsseveralvariabledefinitions.Inthefile
thevariablenamesandvaluesareseparatedbyequalssigns(=).
Emptylinesandlinesstartingwithahashmark(#)areignored.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttrueforthisvariabletobeincluded.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalseforthisvariabletobeincluded.

Variableswhichhavebeendefinedinthiswaycanbeincludedintothesourcecodewiththe//#=
preprocessingdirectiveandcanbecheckedwiththe[variable-name]:definedsymbol:
//#ifdef update-url:defined
//#= String url = "${ update-url }";
//#else
String url = "http://www.default.com/update";
//#endif

Variablescanalsobecompared,pleaserefertothedescriptionofthe#ifdirectiveonpage79for
moreinformation.

53
TheBuildProcess

<debug>
Theoptional<debug>elementcontrolstheinclusionofdebuggingmessagesforspecificclassesor
packages.Thedebuggingmessageswillbeactivatedordeactivatedinthesourcecode,sothe
performancewillnotbedecreased,whenthedebuggingisdeactivated.
<debug showLogOnError="true" verbose="false" level="error" if="test" >
<filter pattern="com.company.package.*" level="info" />
<filter pattern="com.company.package.MyClass" level="debug" />
</debug>

Inthesourcecodeanydebugmessagesmustbeaccompaniedbya//#debugdirective:
//#debug
System.out.println("initialization done.");
or
//#debug warn
System.out.println("could not load something...");
or
//#debug error
System.out.println("could not load something: " + e);

InthechapterTheworldofpreprocessingonpage82youwillfindmoreaboutthedebugging
possibilities.

debugAttribute Required Explanation


level No Thegeneraldebuglevelwhichisneededfordebugmessages.
Possiblevaluesaredebug,info,warn,error,fatalora
userdefinedlevel.Defaultlevelisdebug,soalldebugging
messageswillbeincluded.
verbose No Eithertrueorfalse.Whentruethetime,classnameand
linenumberwillbeincludedineachdebuggingmessage.
Defaultstofalse.Whentheverbosemodeisenabled,the
preprocessingsymbolpolish.debugVerbosewillbedefined.
IntheverbosemodeexceptionsthrownbyJ2MEPolishwill
containusefulinformation.Alsothekeyhandlingand
animationhandlingwillbemonitoredanderrormessageswillbe
givenout.
showLogOnError No Eithertrueorfalse.Whentruethelogcontainingall
loggingmessageswillbeshownwhenanexceptionislogged.
Anexceptionisloggedbyprintingoutamessagewhichis
followedbyaplusandtheexceptionvariable:
//#debug error
System.out.println("could not load something: " +
e);
Thelogcanonlybeshownautomatically,whentheJ2MEPolish
GUIisused.

54
TheBuildProcess

debugAttribute Required Explanation


if No ThenameoftheAntproperty,whichneedstobetrueoryes,
whenthis<debug>elementshouldbeused.Whenthe<debug>
elementisactivated,thepreprocessingsymbol
polish.debugEnabledwillbedefined.
unless No ThenameoftheAntproperty,whichneedstobefalseorno,
whenthis<debug>elementshouldbeused.

Forafinercontrolofthedebuggingprocess,the<debug>elementallowsthesubelement<filter>,
whichdefinesthedebuglevelforspecificclassesorpackages.

filterAttribute Required Explanation


pattern Yes Thenameoftheclassorofthepackage.Whenthepatternends
withastar,allclassesofthatpackagewillbeincluded,e.g.
com.company.mypackage.*
level Yes Thedebugginglevelforallclasseswiththespecifiedpattern.
Possiblevaluesaredebug,info,warn,error,fatalora
userdefinedlevel.

<jad>
Withthe<jad>elementuserdefinedattributescanbeaddedtotheJAD1fileaswellasthe
MANIFESTfilewhichiscontainedinthecreatedJARfile.The<jad>elementcontainsanumber
of<attribute>subelementswhichdefinetheactualattributes:
<jad>
<attribute
name="Nokia-MIDlet-Category"
value="Game"
if="polish.group.Series40"
/>
<attribute
name="MIDlet-Push-1"
value="socket://:79, com.sun.example.SampleChat, *"
if="polish.midp2"
/>
</jad>

attributeAttribute Required Explanation


name Yes Thenameoftheattribute,e.g.NokiaMIDletCategory
unless
fileis
used
value Yes Thevalueoftheattribute.

1 JavaApplicationDescriptor

55
TheBuildProcess

attributeAttribute Required Explanation


unless
fileis
used
file No Thefilewhichcontainsseveralattributedefinitions.Inthefile
theattributenamesandvaluesareseparatedbycolons(:).
Emptylinesandlinesstartingwithahashmark(#)areignored.
target No Eitherjad,manifestorjad,manifest.Anuserdefined
attributeisaddedtoboth,theMANIFESTaswellastheJAD,by
default.Thespecificationsaysuserdefinedattributesshould
onlybeaddedtotheJADfile,buttherearesomedevicesout
therewhichexpecttheseattributesintheMANIFESTaswell.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttrueforthisattributetobeincluded.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalseforthisattributetobeincluded.

Attributeswhicharedefinedinthiswaycanbeloadedintheapplicationwiththe
MIDlet.getAppProperty(Stringname)method,whichneedsthenameoftheattributeasan
argumentandreturnsthevalueofthatargument.Oftenitisadvisabletousethevariable
mechanismofJ2MEPolishinstead,sincesuchvaluesareactuallyhardcodedintotheapplication
andare,therefore,muchfasterthanthegetAppProperty(...)mechanism.

SortingandFilteringJADattributes

TheJADattributescanfilteredandsortedusingthe<jadFilter>subelement:
<jad>
<attribute
name="Nokia-MIDlet-Category"
value="Game"
if="polish.group.Series40"
/>
<jadFilter>
MIDlet-Name, MIDlet-Version,
MIDlet-Vendor, MIDlet-Jar-URL, MIDlet-Jar-Size,
MIDlet-Description?, MIDlet-Icon?, MIDlet-Info-URL?,
MIDlet-Data-Size?, MIDlet-*, *
</jadFilter>
</jad>

The<jadfilter>elementcontainsallallowedattributenamesinthedesiredorderandseparatedby
commas.Youcanusedifferentfiltersbyusingthe"if"or"unless"attributes:

jadFilterAttribute Required Explanation


if No TheAntpropertywhichneedstobetrueorthepreprocessing

56
TheBuildProcess

jadFilterAttribute Required Explanation


termwhichneedsresulttruesothatthisfilterisused.
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalsesothatthisfilterisused.

Insideofthe<jadfilter>elementyoucanspecifyallallowedJADattributesinthedesiredorderand
separatedbycommas.Followingsyntaxisused:

jadFilterText Example Explanation


name MIDlet-Name Thecompletenameofarequiredattribute.
namefollowedby MIDlet-Icon? Thecompletenameofanoptionalattribute.
aquestionmark
beginningofa MIDlet-* Allremainingattributeswhichnamesstartwiththegiven
namefollowedby sequencewillbeincludedatthisposition.
astar
star * Allremainingattributeswillbeincludedatthisposition.A
starcanonlypositionedattheendofafilter.

Anoverviewaboutallowedattributescanbefoundat
http://java.sun.com/j2me/docs/wtk2.0/user_html/Ap_Attributes.html.

<manifestFilter>
Themanifestfilterelementcanbeusedtosortandfiltermanifestattributes.Pleasenotethatthe
firstincludedattributeshouldalwaysbetheManifestVersionattribute.Otherwisetheapplication
willmostlikelynotwork:
<manifestFilter>
Manifest-Version, MIDlet-Name, MIDlet-Version, MIDlet-Vendor,
MIDlet-1, MIDlet-2?, MIDlet-3?, MIDlet-4?, MIDlet-5?,
MicroEdition-Profile, MicroEdition-Configuration,
MIDlet-Description?, MIDlet-Icon?, MIDlet-Info-URL?,
MIDlet-Data-Size?
</manifestFilter>

The<manifestFilter>elementcontainsallallowedattributenamesinthedesiredorderand
separatedbycommas.Youcanusedifferentfiltersbyusingthe"if"or"unless"attributes:

manifestFilter Required Explanation


Attribute
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttruesothatthisfilterisused.

57
TheBuildProcess

manifestFilter Required Explanation


Attribute
unless No TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalsesothatthisfilterisused.

Insideofthe<manifestFilter>elementyoucanspecifyallallowedMANIFESTattributesinthe
desiredorderandseparatedbycommas.Followingsyntaxisused:
ManifestFilter Example Explanation
Text
name MIDlet-Name Thecompletenameofarequiredattribute.
namefollowedby MIDlet-2? Thecompletenameofanoptionalattribute.
aquestionmark
beginningofa MIDlet-* Allremainingattributeswhichnamesstartwiththegiven
namefollowedby sequencewillbeincludedatthisposition.
astar
star * Allremainingattributeswillbeincludedatthisposition.A
starcanonlypositionedattheendofafilter.

Anoverviewaboutallowedattributescanbefoundat
http://java.sun.com/j2me/docs/wtk2.0/user_html/Ap_Attributes.html.

<preprocessor>
The<preprocessor>elementcanbeusedtointegrateownorthirdpartypreprocessors.Thiscanbe
usedforallowingnewpreprocessingdirectivesforexample(comparepage159).
<preprocessor
class="com.company.preprocess.MyPreprocessor"
classPath="import/preprocessing.jar"
>
<parameter
name="scriptFile"
value="../scripts/preprocess.script"
/>
</preprocessor>

preprocessor Required Explanation


Attribute
class Yes Theclassofthepreprocessor.
classPath No Theclasspathforthepreprocessor.
if No ThenameoftheAntproperty,whichneedstobetrueoryes,
whenthis<preprocessor>elementshouldbeused.
unless No ThenameoftheAntproperty,whichneedstobefalseorno,

58
TheBuildProcess

preprocessor Required Explanation


Attribute
whenthis<preprocessor>elementshouldbeused.

Thepreprocessorcanbeconfiguredusinganumber<parameter>subelements.Each<parameter>
subelementneedstodefinetheattributesnameandvalue.

<java>
The<java>elementcanbeusedtoextendJ2MEPolishwithanyJavautility.Itacceptsallattributes
andnestedelementsliketheAnt<java>element(compare
http://ant.apache.org/manual/CoreTasks/java.html)aswellastheadditionalattributeif,unless
andmessage.J2MEPolishvariablescanbeusedinthenested<arg>elements,sothatthecallcan
beadjustedforthecurrentdevice.
Eachdefined<java>elementiscalledafterthesuccessfulcreationofanapplicationbundle.A
possibleuseofthe<java>elementisthesigningofMIDlets,whichisdescribedinthesigning
howtoonpage186.
ThefollowingexamplecallstheJadUtil.jaroftheWirelessToolkitforsigningaJADfile:
<java jar="${wtk.home}/bin/JadTool.jar"
fork="true"
failonerror="true"
if="polish.midp2"
unless="test"
message="Adding signature for device ${polish.identifier}"
>
<arg line="-addjarsig"/>
<arg line="-keypass ${password}"/>
<arg line="-alias SignMIDlet"/>
<arg line="-keystore midlets.ks"/>
<arg line="-inputjad dist/${polish.jadName}"/>
<arg line="-outputjad dist/${polish.jadName}"/>
<arg line="-jarfile dist/${polish.jarName}"/>
</java>

Followingvariablescanbeusedinthe<arg>elementandthemessageattribute:

variable Explanation
polish.vendor Thevendorofthecurrentdevice,e.g.SiemensorNokia.
polish.name Thenameofthecurrentdevice,e.g.NGage.
polish.identifier Theidentifierofthecurrentdevice,e.g.Siemens/SX1.
polish.version Theversionoftheapplicationasdefinedintheinfosection.
polish.jarName Thenameofthejarfileasdefinedintheinfosection.
polish.jadName Thenameofthejadfileasdefinedintheinfosection.

59
TheBuildProcess

Themostimportantattributesofthe<java>elementare:

javaAttribute Required Explanation


classname either Thenameoftheclasswhichshouldbeexecuted.
classname
orjar
jar either Thelocationofthejarfiletoexecute(musthaveaMainClass
classname entryinthemanifest).Forkmustbesettotrueifthisoptionis
orjar selected.
fork No IfenabledtriggerstheclassexecutioninanotherVM(disabled
bydefault).
message No Amessagewhichwillbeprintedoutonthestandardoutput
whenthis<java>elementisexecuted.Themessagecancontain
J2MEPolishvariables,suchas${polish.identifier}.
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttruewhenthis<java>elementshould
beexecuted.
unless No TheAntpropertywhichneedstobefalseorthe
preprocessingtermwhichneedsresultfalsewhenthis<java>
elementshouldbeexecuted.

Themostimportantnestedelementisthe<arg>element:
argAttribute Required Explanation
line No Aspacedelimitedlistofcommandlinearguments.

PleaserefertotheAntdocumentationathttp://ant.apache.org/manual/CoreTasks/java.htmlformore
informationaboutthe<java>element.

<packager>
UsuallytheefficientinternalJ2MEPolishpackagerisusedforcreatingthefinalapplication
bundles.Forusingadifferentpackagingprogram,the<packager>elementcanbeused:
<packager
executable="jar"
arguments="cvfM;;${polish.jarPath};;-C;;${polish.packageDir};;."
/>

Amuchsimplerbutequallyvalidcallisthis:
<packager name="jar" />

ApossiblealternativemightbetheOpenSourcetool7Zip,whichcancreatesmallerfiles

60
TheBuildProcess

comparedtothestandardZIPmechanism.Thismightresultinproblemsontheactualdevice,
though,sousewithcare.The7Ziptoolcanbeobtainedfreeofchargeathttp://www.7zip.org/.
The<packager>elementsupportsfollowingattributes:

packagerAttribute Required Explanation


name Yes,unless Thenameofthepackager,e.g.jar,antcall,7zipor
executable kzip.Youcanregisteryourownpackagerin
orclassis ${polish.home}/customextensions.xmlbyusingthepackager
defined type.
target No TheAnttargetthatshouldbeusedforthepackagingstep.Only
relevantwhentheantcallpackagerisused.
executable No Thenameoftheprogram,e.g.jaror7za.exe.
arguments No Theargumentsforthepackagerwhenyouhavedefinedthe
executableattribute.Severalargumentscanbeseparatedby
usingdoublesemicolons(;;).AnyAntpropertiesaswellas
J2MEPolishvariablescanbeused.Oftenneededvariablesare:
${polish.jarPath}:thefullpathtothejarfilewhichshould
becreated.
${polish.packageDir}:thedirectorywhichcontainsthe
classesandtheresourceswhichshouldbejared.
class No Thenameoftheclasswhichextendsthe
de.enough.polish.jar.Packagerclass.Thismechanismcan
beusedforextendingthepackagingcapabilitiesofJ2ME
Polish.
Inthatcasefurtherparameterscanbesetusingnested
<parameter>elements.

The<emulator>Section
The<emulator>elementisresponsibleforlaunchinganyemulatorsaftertheapplicationhasbeen
build.
<emulator
wait="true"
trace="class"
preferences="myemulator.properties"
securityDomain="trusted"
enableProfiler="true"
enableMemoryMonitor="true"
enableNetworkMonitor="true"
if="test"
>
<parameter name="-Xjam"
value="transient=http://localhost:8080/${polish.jadName}" />

61
TheBuildProcess

</emulator>

Intheaboveexampletheemulatorisonlystarted,whenthetestpropertyistrue.

Attributesofthe<emulator>Section
The<emulator>elementsupportsfollowingattributes:

emulatorAttribute Required Explanation


wait No Eitheryes/trueorno/false.DefineswhethertheJ2ME
Polishtaskshouldwaituntiltheemulatorisfinished.Thisis
neededwhenanyoutputshouldbeshownontheAntoutput,
thereforewaitdefaultstoyes.
trace No Definesifanyvirtualmachineactivitiesshouldbeshownon
theoutput.Possiblevaluesareclassforshowingtheloading
ofclasses,gcforactivitiesofthegarbagecollectionandall
foraveryextensiveoutput.Severalvaluescanbegivenwhen
theyareseparatedbycomma,e.gclass,gc.
securityDomain No TheMIDP/2.0securitydomainoftheapplication:either
"trusted","untrusted","minimum"or"maximum".Intrusted
andmaximummodeallsecuritysensitiveactivitiesare
allowed;intheuntrustedmodetheuserwillbequestioned
beforeeachsecuritysensitiveactivityandintheminimum
modeanysecuritysensitiveactivitywillnotbeallowed.
enableProfiler No Eitheryes/trueorno/false.Whenactivatedthe
performancewillbeprofiledduringtheexecutionofthe
application.Theresultswillbeshownwhentheemulatoritself
isclosed.
enableMemoryMonit No Eitheryes/trueorno/false.Whenactivatedthe
or memoryusageoftheapplicationwillbeshown.
enableNetworkMonit No Eitheryes/trueorno/false.Whenanynetwork
or activitiesaredone,amonitorwillshowdetailsofthesentand
receiveddata.
preferences No Thefilewhichcontainstheemulatorpreferences.Whensucha
fileisused,theprofilerandmonitorsettingsareignored.Please
consultthedocumentationoftheWirelessToolkitfordetailed
informationaboutthepreferencesfile.
showDecompiledSta No Eitheryes/trueorno/false.Determineswhethera
ckTrace decompiledstacktraceshouldbeshown,evenwhenthesource
codepositionofanexceptioncouldbebelocated.The
automaticresolvingofstacktracesisdiscussedbelow.
if No TheAntpropertywhichneedstobetruewhenthe

62
TheBuildProcess

emulatorAttribute Required Explanation


<emulator>elementshouldbeexecuted.
unless No TheAntpropertywhichneedstobefalsewhenthe
<emulator>elementshouldbeexecuted.

The<parameter>Subelement
The<emulator>elementsupportsthenestedsubelement<parameter>fordefiningadditional
commandlineparameters:

parameterAttribute Required Explanation


name Yes Thenameoftheparameter.
value Yes Thevalueoftheparameter,thevaluecanuseanyJ2MEPolish
oruserdefinedvariable,thefollowingvariablesareespecially
useful:
${polish.jadName}:ThenameoftheJADfile
${polish.jadPath}:TheabsolutepathoftheJADfile
${polish.jarName}:ThenameoftheJARfile
${polish.jarPath}:TheabsolutepathoftheJARfile
${polish.classes.midlet-1}:ThemainMIDletclass
${polish.classes.midlet-2}:ThesecondMIDletclass,if
any
${polish.classes.midlet-n}:ThenthMIDletclass,ifany

Whenonlyacommandlineswitchshouldbedefined,justdefine
anemptyvalue,e.g.
<parameter name="-Xsomething" value="" />
if No TheAntpropertywhichneedstobetrueorthepreprocessing
termwhichneedsresulttruewhenthisparametershouldbeused.
unless TheAntpropertywhichneedstobefalseorthepreprocessing
termwhichneedsresultfalsewhenthisparametershouldbe
used.

EmulatorSettingsintheDeviceDatabaseandinthebuild.xml
J2MEPolishusesthedevicedatabasetodeterminethecorrectemulator.Ifanemulatorcannotbe
started,youcantellJ2MEPolishhowtolaunchitbymodifyingthesesettings.

WTKEmulators
ForemulatorswhichareintegratedintheWirelessToolkittheEmulator.Skincapabilityisused
fordeterminingthecorrectemulator.Thisisthenamewhichcanbefoundinthe

63
TheBuildProcess

${wtk.home}/wtklib/devicesfolder,e.g.SonyEricsson_P900etc.Whenno
Emulator.Skincapabilityisfound,thecurrentdefaultemulatorwillbestartedinstead.Whenthe
wrongemulatorisstarted,pleasecheckiftheEmulator.Skincapabilityhasbeensetinthe
${polish.home}/devices.xmlfile.Ifthatcapabilityismissing,pleasereportitalsoto
j2mepolish@enough.desothatthedevicedatabasecanbeimproved.

Youcanalsosetseveralskins,whenseveralversionsofanemulatordoexist,forexample.
J2MEPolishwillthenchoosethethefirstemulatoritfinds.Additionalskinsaredefinedbythe
capabilitiesEmulator.Skin.2,Emulator.Skin.3andsoforth.

NokiaEmulators
ForlaunchingSiemensemulatorsitmightbenecessarytodefinethenokia.homepropertyinthe
build.xml.ThispropertyneedstopointtotheinstallationdirectoryoftheNokiaemulatorsand
defaultstoC:\NokiaonWindowsmachinesandto${user.home}/NokiaonUnixmachines.For
manyemulatorsitissufficienttosettheEmulator.ClassandEmulator.Skincapabilitiesof
thedeviceinthe${polish.home}/devices.xmlfile.TheEmulator.Classcapabilitythenneeds
tobeNokiaEmulatorandtheEmulator.Skincapabilityneedstocorrespondwiththenameof
theemulatorwhichcanbefoundinthe${nokia.home}/Devicesdirectory.
SomenonstandardemulatorsmakeitnecessarytheusetheGenericEmulatorclassinstead.The
invocationofsuchemulatorsisexplainedbelow.

SiemensEmulators
ForlaunchingSiemensemulatorsitmightbenecessarytodefinethesiemens.homepropertyin
thebuild.xml.ThispropertyneedstopointtotheinstallationdirectoryoftheSiemensMobile
Toolkit(SMTK)anddefaultstoC:\siemens.WhenaSiemensemulatorshouldbeused,the
correspondingdevicedefinitioninthe${polish.home}/devices.xmlfileneedstosetthe
Emulator.ClasscapabilitytoSiemensEmulator(thisisthedefaultforallSiemensphones).
TheEmulator.Skincapabilityneedstospecifythenameoftheemulator,whichcanbefoundin
the${siemens.home}/SMTK/emulatorsdirectory.

MotorolaEmulators
ForlaunchingMotorolaemulatorsitisnecessarytodefinethemotorola.homepropertyinthe
build.xml.ThispropertyneedstopointtotheinstallationdirectoryoftheMotorolaSDK,e.g.
C:\programfiles\Motorola\SDKv.4.3forJ2ME.SinceMotorolaemulatorsdonotsupportthe
UnifiedEmulatorInterface,theemulatorsarestartedbytheGenericEmulator.Seebelowfor
moredetails.

LaunchinganyEmulatorwiththeGenericEmulatorImplementation
YoucanstartanykindofemulatorwiththeGenericEmulatorclass.Youshouldsetthe
Emulator.Classcapabilityofthecorrespondingdevicedefinitioninthe
${polish.home}/devices.xmlfiletoGenericEmulator.
TheEmulator.Executablecapabilityneedstodefinetheprogramwhichshouldbestarted,e.g.
javaor${motorola.home}/EmulatorA.1/bin/emujava.exe.Thisprogramisresponsiblefor
startingtheemulator.

64
TheBuildProcess

Youneedalsotodefinethecommandlineargumentsfortheemulatorwiththe
Emulator.Argumentscapability.Commandlineargumentsareseparatedbytwosemicolonsina
row,e.g.Xdescriptor;;${polish.jadPath};;classpath;;${polish.jarPath}.Asyoucanseeinthe
example,anyJ2MEPolishvariablesaswellasAntpropertiescanbeusedwithintheemulator
arguments.Oftenusedisthepolish.jadPathvariable,whichcontainstheabsolutepathtothe
JADfileandthepolish.jarPathvariable,whichdoesthesamefortheJARfile.Alsousefulisthe
polish.classes.midlet-1variablethatcontainsthenameofthefirstMIDletclass.
Youshouldtrytominimizethedependencyonaspecificsystemsetupbyusingpropertieslike
motorola.homeornokia.homeinyoursettings.Thesepropertiescanthenbedefinedwithinthe
correspondingbuild.xmlfile.
PleaseinformtheJ2MEPolishcommunityaboutanyemulatorsyouhaveintegrated,sothatother
userscanalsobenefitfromyoursettings.Justsendanemailtoj2mepolish@enough.de.Thanks!

AutomaticResolvingofStackTracesandExceptions
J2MEPolishcanresolvestacktraceslikeException at
com.company.MyClass.doSomething(+200)automatically,whenthefreejaddecompileris
installed.Thisdecompilercanbedownloadedathttp://www.kpdus.com/jad.html.Pleaseadjust
thePATHenvironmentvariable,sothatitincludestheinstallationdirectoryofjadorinstallthejad
excecutable(jad.exeorjad)tothe${polish.home}/binfolder.
Whenjadisinstalledcorrectly,J2MEPolishwillresolvestacktracesautomatically.Insteadof
seeingonlytheratherobscurestacktracepackage.class.method(+instructionoffset),an
additionalmessagegivingthesourcelocationaswellasthefaultysourcecodeisprintedout,e.g.
src/com/company/MyClass.java:97: int result = max / 0;.IfyouexecuteJ2MEPolish
fromwithinanIDE,youcanclickonsuchamessageandtheneditthefaultycodedirectly.
IncaseswhenJ2MEPolishisnotabletolocatethepositioninthesourcecode,anextractofthe
decompiledclasscodewillbeshowninstead.Thisextractwillhelpyoutoidentifythesourceofthe
error.Thefollowingfragmentgivesanexampleofadecompiledclasscode:
world.animate(System.currentTimeMillis() - lastCycleTime);
// 87 169:aload_0
// 88 170:getfield #13 <Field World world>
// 89 173:invokestatic #17 <Method long System.currentTimeMillis()>
// 90 176:lload 4
// 91 178:lsub
// 92 179:invokevirtual #23 <Method void World.animate(long)>

Inthefirstlinetheactualdirectiveisgivenandinthefollowinglinesthebinaryequivalent
compiledjavacodeislisted.Thesecondnumberfromtheleftisthenumberwhichisgiveninthe
originalerrormessage(e.g.package.class.method(+179)).
WhentheshowDecompiledStackTraceattributeofthe<emulator>elementissettotrueor
yes,adecompiledcodefragmentwillbegivenoutforeachstacktrace,evenwhenthesource
codepositioncouldbelocated.
Pleasenotethatthesourcecodepositioncanonlybelocated,whenthedebuggingmodeis
activated.Thisisdonebysettingtheenableattributeofthe<debug>elementtotrue.Inthe
defaultsetupthisisdonewhenthetesttargetofthebuild.xmliscalledfirst:

65
TheBuildProcess

ant test j2mepolish.

66
ResourceAssembling

ResourceAssembling
Concepts
Duringthebuildprocessresourceslikeimages,soundfilesetc.areassembledautomaticallyfor
eachdevice.
Resourcesforalldeviceswillbeplacedintotheresourcesfolder(whennootherdirectoryhas
beenspecifiedinthe<resources>elementorwiththeresDirattributeofthe<build>elementin
thebuild.xmlfile).
Resourcesfordevicesofspecificvendorscanbeplacedintotheresources/[vendorname]folder,
e.g.theresources/NokiafolderforNokiadevices.Resourcesforaspecificdevicecanbeplaced
intotheresources/[vendorname]/[devicename]folder,e.g.thefolderresources/Nokia/3650for
Nokia/3650devices.
Formoregeneralresourcesthegroupscanbeusedtowhichadevicebelongsto.Highcolorimages
canbebeputintotheresources/BitsPerPixel.16+folder,forexample.Thegroupscanbeused
veryefficientlytoincludeonlythoseresourceswhichareactuallyrelevantforaspecificdevice.A
devicecanbelongtomanydifferentgroups,whicharedefinedeitherimplicitlybythecapabilities
ofthatdevice(comparethesectionDeviceCapabilitiesonpage26)orexplicitlybysettingthe
<groups>elementofadeviceinthedevicedatabase.
Allresourceswillbecopiedtotherootoftheapplicationandmorespecificresourceswilloverwrite
thecommonresources:Ifyouhaveapicturenamedhello.pngintheresourcesfolderaswellas
intheresources/Nokiaandintheresources/Nokia/6600folder,theversionintheresources
folderwillbeusedforallnonNokiadevices,theversioncontainedintheresources/Nokiafolder
willbeusedforallNokiadevices,buttheimageresources/Nokia/6600/hello.pngwillbeusedfor
theapplicationwhichisbuildfortheNokia/6600phone.Intheapplicationcodeyoucanloadthis
imagefromtheroot:Image.createImage( "/hello.png" ),nomatterfromwheretheresource
wascopiedfrom.
Nosubfolderscanbeusedwithinanapplication,soitisnotpossibletoloadresourcesfroma
subfolderwithintheapplication.Subfoldersdoaddoverheadtoanapplication,thisiswhytheusage
ofsubfoldersisnotallowed.
Insteadof
// this is not allowed:
InputStream is = getClass().getResourceAsStream("/levels/level.map");

thefollowingcodeneedstobeused:
InputStream is = getClass().getResourceAsStream("/level.map"); // this is ok

Subfoldersaremerelyusedtodifferentiatebetweendifferentdevicesanddevicegroups.

OftenUsedGroups
ForacompletelistofgroupspleaserefertothesectionDeviceCapabilitiesonpage26,the
HTMLdocumentationalsolistsallgroupsforeachdevicecontainedinthedevicedatabase.Herea
coupleofexamples:

67
ResourceAssembling

Group Type DefaultFolder Explanation


ScreenSize.17 Screen resources/ScreenSize.1 Folderfordifferentscreensizesofthetarget
6x208 76x208 devices,e.g.ScreenSize.176x208or
ScreenSize.128x128andsoon.
ScreenSize.17 Screen resources/ScreenSize.1 Folderfordeviceswithscreensthatareaslarge
0+x200+ 70+x200+ orlargerthanthespecifiedscreensize.Inthe
examplethescreenneedstobeatleast170
pixelswideand200pixelhighsothatresources
fromthatfolderareincluded.
CanvasSize.17 Canvas resources/CanvasSize.1 Folderfordifferentcanvassizesofthetarget
6x208 76x208 devices,e.g.CanvasSize.176x208or
CanvasSize.128x128andsoon.
CanvasSize.1 Canvas resources/CanvasSize.1 Folderfordeviceswithcanvassesthatareas
70+x200+ 70+x200+ largeorlargerthanthespecifiedcanvassize.In
theexamplethecanvasneedstobeatleast170
pixelswideand200pixelhighsothatresources
fromthatfolderareincluded.
FullCanvasSi FullCan resources/FullCanvasSi Folderfordifferentfullscreenmodecanvassizes
ze.176x208 vas ze.176x208 ofthetargetdevices,e.g.
FullCanvasSize.176x208or
FullCanvasSize.128x128andsoon.
FullCanvasSi FullCan resources/FullCanvasSi Folderfordeviceswithcanvassesthatareas
ze.170+x200+ vas ze.170+x200+ largeorlargerthanthespecifiedcanvassizein
fullscreenmode.Intheexamplethecanvas
needstobeatleast170pixelswideand200
pixelhighinfullscreenmodesothatresources
fromthatfolderareincluded.
Series60 Platform resources/Series60 FolderforSymbianSeries60devices.
Series40 Platform resources/Series40 FolderforSymbianSeries40devices.
midp1 Platform resources/midp1 WhenadevicesupportstheMIDP/1.0platform,
resourcesforthisdevicecanbeplacedintothe
resources/midp1folder.
midp2 Platform resources/midp2 FordevicessupportingtheMIDP/2.0platform.
cldc1.0 Configu resources/cldc1.0 FordevicessupportingtheCLDC/1.0
ration configuration.
cldc1.1 Configu resources/cldc1.1 FordevicessupportingtheCLDC/1.1
ration configuration.
mmapi api resources/mmapi WhenadevicesupportstheMobileMediaAPI,
resourceswhichneedthisAPIcanbeplaced
intotheresources/mmapifolder.

68
ResourceAssembling

Group Type DefaultFolder Explanation


motorolalwt api resources/motorolalwt FordeviceswhichsupportMotorola's
LightweightWindowingToolkitAPI.
nokiaui api resources/nokiaui FordeviceswhichsupportNokia'sUser
InterfaceAPI.
wav audio resources/wav FordeviceswhichsupporttheWAVsound
format.
mp3 audio resources/mp3 FordeviceswhichsupporttheMP3sound
format.
amr audio resources/amr FordeviceswhichsupporttheAMRsound
format.
midi audio resources/midi FordeviceswhichsupporttheMIDIsound
format.
mpeg4 video resources/mpeg4 FordeviceswhichsupporttheMPEG4video
format.
h.263 video resources/h.263 Fordeviceswhichsupporttheh.263video
format.
3gpp video resources/3gpp Fordeviceswhichsupportthe3GPPvideo
format.
BitsPerPixel.1 colors resources/BitsPerPixel. Fordeviceswithacolordepthofatleast12bits
2+ 12+ percolor.
BitsPerPixel.1 colors resources/BitsPerPixel. Fordeviceswithacolordepthofexactly16bits
6 16 percolor.

FineTuningtheResourceAssembling
Sometimesitisnecessarytoadjusttheresourceassembling.
ImaginethesituationwhereyouhaveanapplicationwhichusesMP3soundfileswhenthedevice
supportsMP3,andMIDIsoundfileswhenthedevicesupportsMIDI.Inthesourcecodeyoucanuse
thepreprocessingsymbolspolish.audio.mp3andpolish.audio.miditodistinguishbetweenthese
cases:
//#ifdef polish.audio.mp3
// okay play the mp3 sound
//#elifdef polish.audio.midi
// play midi sound instead
//#endif

Thesituationisdifferentintheresourceassemblingstep,though.ObviouslyyoucanputallMP3
filesintotheresources/mp3folderandallMIDIfilesintotheresources/midifolder,sothat
theseresourcesareavailablewhentheyareneeded.ButfordeviceswhichsupportbothMP3aswell
asMIDIsound,theapplicationwillcontaintheMIDIfilesaswell,eventhoughonlytheMP3files

69
ResourceAssembling

areactuallyneeded.
Forsuchcasesyoucandefinefilesetsinthebuild.xmlwhichwillbeincludedwhenspecific
conditionsarefulfilled:
<resources
dir="resources"
excludes="readme*"
>
<fileset
dir="resources/multimedia"
includes="*.mp3"
if="polish.audio.mp3"
/>
<fileset
dir="resources/multimedia"
includes="*.mid"
if="polish.audio.midi and not polish.audio.mp3"
/>
</resources>

IntheaboveexampleMIDIfilesareonlyincludedwhentwoconditionsaremet:
1) ThedevicesupportsMIDIsound
2) ThedevicedoesnotsupportMP3sound.
The<resources>elementisasubelementofthe<build>section,lookatpage41fordetailed
informationaboutthesupportedattributesaswellasthenestedelements.Anoftenusedattributeis
theexcludeattributewhichspecifiesanyfileswhichshouldnotbeincludedintotheapplication
bundle.Youcanhavereadmefilesforexamplewithbackgroundinformationfordesigners.Inthe
aboveexampleallfilesstartingwithreadmeareexcludedfromthefinalapplicationJARfile.
The<resources>elementisalsoresponsibleforthelocalizationoftheapplication,whichis
discussedinthefollowingchapter.
OnafinalnotepleaseremembernottousetheresDirattributeofthe<build>elementwhenyou
usethe<resources>element,sincethiswillyieldunpredictableresults.

Localization
Concepts
Oftenapplicationsshouldnotonlybemarketedinonecountryorregion,butinseveralones.The
processofadjustinganapplicationtoaspecificregioniscalledlocalization.
J2MEPolishoffersaverypowerfulframeworkfornotonlymanagingtheobviousneeded
translations,butalsoforadjustinganykindofresourceslikeimagesorsoundstospecificregions.
EvenenhancedfeatureslikelocaleawaredateformattingisnoproblemwithJ2MEPolish.
Traditionallylocalizationinvolvedloadingthelocalizedmessagesfromafileduringruntimeand
retrievingthesemessageswithHashtablekeys.Thissignificantlyslowsdownalocalized
applicationandalsoenlargestheapplicationsize.AuniquefeatureofJ2MEPolishisthatthe
translationsareactuallydirectlyembeddedintothesourcecode,soinmostcasesalocalized
applicationhasabsolutelynooverheadatallcomparedtoanonlocalizedapplicationbothinsize

70
Localization

aswellasinperformance.
Youcanalsoenabledynamictranslationsthatcanbechangedduringtheruntimeoftheapplication.
InthatcaseanyStringkeysareconvertedintosimpleintegerkeysduringthepreprocessingphase
sothattranslationscanberetrievedasfastaspossible.
Thelocalizationframeworkextendstheconceptsoftheresourceassembling,sothatyoucanfor
exampleprovideoneNokiaspecificresourceforeachsupportedlocale.Thelocalizationis
controlledbythe<localization>element,whichisasubelementofthe<resources>element
(comparepages67and41).

The<localization>ElementandLocalizedResourceAssembling
<resources
dir="resources"
excludes="*.txt"
>
<localization locales="de, en, fr_CA" unless="test" />
<localization locales="en" if="test" />
</resources>

The<localization>elementisresponsiblefordefiningwhichlocalesshouldbesupported.Inthe
aboveexamplethelocalesde(German)anden(English)areused,unlessthetestmodeis
active,inwhichcasetheapplicationisonlybuildfortheEnglishlocale.
LocalesaredefinedusingtheISOstandardoftwolowercaselettersforthelanguage2(enfor
English,deforGerman,frforFrenchandsoon)andtwooptionaluppercaselettersforthe
country3(USforUSA,DEforGermany,FRforFranceandsoon).Possiblecombinations
separatethelanguageandtheregionwithanunderline.YoucanlocalizeyourapplicationforFrench
speakingCanadiansbysupportingthelocalefr_CAforexample.
Ineachusedresourcesfolderyoucancreateasubfolderforaspecificlocale,e.g.resources/enfor
generalEnglishresourcesandresources/fr_CAforresourcesfortheFrenchspeakingCanadians.
Theusualspecificationrulesalsoapplyhere,soamorespecificresourceinresources/Nokia/en
willoverridearesourcewiththesamenameinresources/NokiawhentheEnglishlocaleisused.

ManagingTranslations

TheLocaleClass
Thede.enough.polish.util.Localeclassisusedfortheretrievaloftranslations.Itoffersthree
distincttranslationmethods:
static String get( String name ),

static String get( String name, String parameter ),and

static String get( String name, String[] parameters ).

Thefollowingcodeillustratestheusageofthesemethods:
import de.enough.polish.util.Locale;

2 ISO639,comparehttp://www.ics.uci.edu/pub/ietf/http/related/iso639.txt
3 ISO3166,comparehttp://www.chemie.fuberlin.de/diverse/doc/ISO_3166.html

71
Localization

[...]

// getting a simple translation:


this.menuScreen.append( Locale.get( "menu.StartGame"), null);
// getting a translation with one parameter:
this.menuScreen.setTitle( Locale.get( "title.Main", userName ), null);
// getting a translation with several parameters:
String[] parameters = new String[2];
parameters[0] = userName;
parameters[1] = enemyName;
this.textField.setString( Locale.get("messages.Introduction", parameters ) );

Youneedtoputthe${polish.home}/import/enough-polish-client.jarontheclasspathof
yourprojecttousetheLocaleclassinyourIDE.
Intheresources/messages.txttheabovelocalizationsneedtobedefined:
menu.StartGame=Start Tickle Fight
# the title of the main-screen with the user-name as the only parameter:
title.Main=Welcome {0}!
# the intro for a new game with following parameters:
# {0}: the name of the player
# {1}: the name of the remote or computer player
messages.Introduction={1} threatens to tickle you!\n{0} against {1} is loading...

Asyoucanseeintheaboveexampleyoucanuseparametersinthetranslations,thefirstparameter
is{0},thesecond{1}andsoon.YoucanalsouseanyJavaspecificcharacters,e.g.\tforatab
or\"forusingaquotationmark.
Thetranslationsareembeddedintheactualcodeduringthepreprocessingphase,ifyouhavealook
atthepreprocessedcode,youwillfindfollowingcode:
import de.enough.polish.util.Locale;

[...]

// getting a simple translation:


this.menuScreen.append( "Start Tickle Fight", null);
// getting a translation with one parameter:
this.menuScreen.setTitle( "Welcome " + userName + "!", null);
// getting a translation with several parameters:
String[] parameters = new String[2];
parameters[0] = userName;
parameters[1] = enemyName;
this.textField.setString( Locale.get(0, parameters ) );

ThetranslationsforthefirsttwoLocalemethodsaredirectlyembeddedintothesourcecode,so
thereisnoperformanceorsizeimpactcomparedtoanonlocalizedapplicationatallforthesekinds
oftranslations.OnlyforthethirdmethodacalltotheLocaleclassisactuallymade,butinthatcall
theformerStringkeymessages.Introductionistransformedtoasimpleinteger,thussaving
valuablebytesaswellasensuringafastretrievaloftheresourceinquestion.

DynamicTranslations
Youcanalsousedynamictranslationsthatcanbechangedduringtheruntimeofyourapplication.
Youhavetoactivatedynamictranslationsbysettingthe"dynamic"attributeofthe<localization>

72
Localization

elementto"true":
<resources
dir="resources"
excludes="*.txt"
>
<localization
dynamic="true"
default="en"
locales="de, en, fr_CA"
/>
</resources>

YoucannowusetheLocaleclassnormally,theonlydifferencetousingstatictranslationsisthatthe
translationsarenotembeddedintoyoursourcecodebutratherretrieveddynamicallyfromthe
Localeclass.ForallowingafastperformanceJ2MEPolishconvertsallStringbasedkeysinto
simpleintegervalues,sothatonlyaminimaloverheadispresent.
YoucanchangethetranslationsbycallingLocale.loadTranslations( String url ).Foreach
supportedlocaleJ2MEPolishgeneratesa[locale-name].locfile,e.g."de.loc","en.loc"or
"fr_CA.loc".YoucanswitchtotheGermantranslationbycallingLocale.loadTranslations(
"/de.loc" ),forexample.Don'tforgettheslashcharacter'/'atthestartoftheURL.

DefiningTranslations
Alltranslationsarebydefaultdefinedinthemessages.txtfile.Alldefaultmessagesaredefinedin
resources/messages.txt,allGermanmessagesinresources/de/messages.txtandall
FrenchCanadianresourcesinresources/fr_CA/messages.txt.Youcanalsousethefiles
resources/messages.txt,resources/messages_de.txtand
resources/messages_fr_CA.txtifyouprefertohavealltranslationsinonefolder.Thenameof
themessagesfilescanbeadjustedwiththemessagesattributeofthe<localization>elementby
theway.
Thetranslationscanbeadjustedbytheusualhierarchyoftheresourceassembling,soifyouhave
Nokiaspecifictranslations,thesecanbedefinedintheresources/Nokia/messages.txtetc.
WhenanapplicationislocalizedfortheNokia/6600phoneandtheGerman(de)language,J2ME
Polishtriestofindatranslationinfollowingplaces:
1. resources/Nokia/6600/de/messages.txt
2. resources/Nokia/6600/messages_de.txt
3. resources/[groupname]/de/messages.txt,e.g.resources/Series60/de/messages.txt
4. resources/[groupname]/messages_de.txt,,e.g.resources/Series60/messages_de.txt
5. resources/Nokia/de/messages.txt
6. resources/Nokia/messages_de.txt
7. resources/de/messages.txt
8. resources/messages_de.txt
Whenthetranslationisstillnotfoundthesamehierarchyissearchedagain,butthistimethedefault

73
Localization

messages.txtfileisused.Ifthetranslationcannotbefound,J2MEPolishwillreporttheerrorand
stopthebuild.Whenalsoaregionisspecified(e.g.fr_CAforFrenchCanadian),J2MEPolish
willfirsttrytogetaspecificfr_CAmessage,e.g.from
resources/Nokia/6600/fr_CA/messages.txt,secondlythetranslationwillbesearchedforthe
language,e.g.resources/Nokia/6600/fr/messages.txt,beforethetranslationisretrieved
fromthedefaultmessagesfile.
Intheactualtranslationfilesyoucaninsertcommentsbystartingthelinewithahashmark(#).
LikeinnormalJavainternationalizationyoucanuseparameterswithinthetranslations,whichare
denotedby{0},{1},{2}andsoon:
menu.StartGame=Start Tickle Fight
# the title of the main-screen with the user-name as the only parameter:
title.Main=Welcome {0}!
# the intro for a new game with following parameters:
# {0}: the name of the player
# {1}: the name of the remote or computer player
messages.Introduction={1} threatens to tickle you!\n{0} against {1} is loading...

SettingandUsingLocalizedVariables
Youcansetlocalizedvariablesjustbydefiningthemintheappropriatemessagesfile.Variable
definitionsneedtostartwitheithervar:orvariable::
var:VirtualCurrency=Nuggets

Suchvariablescanalsobeusedwithinthetranslations(ofcoursenormalvariablescanalsobe
used):
# The player has won some nuggets, {0} specifies the number of won nuggets:
messages.YouHaveWon=Congrats! You have won {0} ${polish.Vendor}-${VirtualCurrency}!

NaturallythevariablescanbeusedduringtheusualpreprocessingintheJavasourcecodeaswell:
//#= String virtualCurrency = "${VirtualCurrency}";

UsingLocalizedAttributes
SomeJARorMANIFESTattributesneedtobelocalizedaswell,e.g.thedescriptionofthe
application.ThiscanbedonebydefiningsuchMIDletattributesintheappropriatemessagesfile:
MIDlet-Description=A game where you need to tickle your enemies!
MIDlet-Name=Tickle-Fight

Pleasecomparethedocumentationofthe<info>sectiononpage31forlearningthenamesofthe
MIDletattributes.

CopingwithDatesandCurrencies
Thede.enough.polish.util.Localeclassofferssomehelpfordealingwithlocalizedcontent:
static String formatDate( Calendar calendar )formatsadatespecifictothecurrent
locale,thismethodisalsoavailableforDateandlong.
static String LANGUAGEisafieldholdingtheISOlanguagecode.

74
Localization

static String COUNTRYisafieldholdingtheISOcountrycode.Thisisnullwhennocountry


isusedinthecurrentlocale.
static String DISPLAY_LANGUAGEisafieldholdingthelocalizedlanguagename,e.g.
DeutschforGerman.
static String DISPLAY_COUNTRYisafieldholdingthelocalizedcountryname,e.g.
DeutschlandforGermany.Thisisnullwhennocountryisusedinthecurrentlocale.
static String CURRENCY_SYMBOLisafieldholdingthesymboloftheusedcurrency,e.g.$
or.Thisisnullwhennocountryisusedinthecurrentlocale.
static String CURRENCY_CODEisafieldholdingthethreelettercodeoftheusedcurrency,
e.g.USDorEUR.Thisisnullwhennocountryisusedinthecurrentlocale.

CommonTraps

AdjustingtheJARname
YouneedtoremembertoadjusttheJARnameoftheapplicationinthe<info>sectionofthe
build.xml,sothatthelocaleisincluded,otherwiseonlythelastlocalizedapplicationisactually
writtentothedistfolder.Youcanusethevariables${polish.locale}e.g.fr_CA,
${polish.language}e.g.fr,and${polish.country}e.g.CAinthejarNameattribute.
AnexamplejarNameattributeisthefollowing:
<info [...]
jarName="${polish.vendor}-${polish.name}-${polish.locale}-example.jar"

UsingQuotationMarksandOtherSpecialCharactersinTranslations
Youcanusequotationmarksaswellasanyspecialcharacterifyouescapethemdirectly,usually
withabackslashcharacter\atthestart,e.g.:
Quotationmarks:\"
Tab:\t
Backslash:\\
andsoon.
InthetranslationsallstandardJavaescapesequencesaresupported.

InvalidLocaleCalls
Pleaseensurethatthekeyofthetranslationisalwaysgivendirectlyinsteadofusingavariable,
otherwiseJ2MEPolishwillnotbeabletoembedthetranslationcorrectlyandyouendupwith
compileerrors.Thefollowingexamplemustnotbeused:
// never do this:
String key = "menu.StartGame";
this.menuScreen.append( Locale.get( key ), null);

Insteadusethekeydirectlyinthecallasinthisexample:

75
Localization

// this is just fine:


this.menuScreen.append( Locale.get( "menu.StartGame" ), null);

Whenyouhaveseveralparameters,theparametersneedtobegiveninavariable,otherwiseJ2ME
Polishisagainunabletoprocessthecallcorrectly:
// never do this:
this.menuScreen.append( Locale.get( "game.StartMessage" ), new String[]{ userName,
enemyname } );

Insteaddefinetheparametersbeforetheactualcall:
// this is just fine:
String[] parameters = new String[]{ userName, enemyname };
this.menuScreen.append( Locale.get( "game.StartMessage" ), parameters );

LocalizingtheJ2MEPolishGUI
TheJ2MEPolishGUIusesseveraltexts,whichcanbelocalizedusingvariables.Thefollowing
variablescanbeseteitherinthebuild.xmlorwithinthemessages.txtfile:
Variable Default Explanation
polish.command.ok OK ThelabelfortheOKmenuitem,whichisusedScreen
menuswhenthemenufullscreenmodeisused.
polish.command.cancel Cancel ThelabelfortheCancelmenuitem.
polish.command.select Select ThelabelfortheSelectmenuitem,whichisusedbyan
implicitorexclusiveListorChoiceGroup.
polish.command.mark Mark ThelabelfortheMarkmenuitemofamultipleListor
ChoiceGroup.
polish.command.unmark Unmark ThelabelfortheUnmarkmenuitemofamultipleListor
ChoiceGroup.
polish.command.options Options Thelabelforthemenuwhenseveralmenuitemsare
available.
polish.command.delete Delete ThelabelfortheDeletemenuitem,whichisusedby
TextFields.
polish.command.clear Clear ThelabelfortheClearmenuitem,whichisusedby
TextFields.
polish.title.input Input ThetitleofthenativeTextBoxwhichisusedfortheactual
inputoftext.Thistitleisonlyused,whenthecorresponding
TextFielditemhasnolabel.WhentheTextFieldhasalabel,
thatlabelisusedasatitleinstead.

Thefollowingexampleshowsthedefinitionofsomeofthesevariableswithinamessages.txtfile:
var:polish.command.cancel=Abbruch

76
Localization

var:polish.command.delete=Lschen
var:polish.title.input=Eingabe

Thisexampleshowsthedefinitionofsomeofthesevariableswithinthebuild.xmlfile.This
approachisusefulwhennocompletelocalization/internationalizationshouldbedone:
<variable name="polish.command.cancel" value="Abbruch" />
<variable name="polish.command.delete" value="Lschen" />
<variable name="polish.title.input" value="Eingabe" />

77
TheWorldofPreprocessing

TheWorldofPreprocessing
Preprocessingchangesthesourcecodebeforeitiscompiled.Withthismechanismanydevice
optimizationcanbedoneeasily.AnexampleistheinclusionoftheJ2MEPolishGUI,whichcanbe
includedwithoutanyinterventionofthedeveloper.
Mostpreprocessingistriggeredbydirectives,whichuseeithersymbolsorvariables.Asymbolis
likeabooleanvalueeitheritisdefinedorthesymbolisnotdefined.Avariable,however,always
containsavalue,whichcanbeusedorcomparedduringthepreprocessing.
Symbolsandvariablesaredefinedinseveralfiles:
build.xml:withthesymbolsattributeofthe<build>elementandwiththe<variables>
element
vendors.xml,groups.xml,devices.xml:symbolsaredefinedbythe<features>element,whereas
variablesaredefinedbythecapabilities.Mostcapabilitiesalsodefinesymbols,seethesection
Capabilitiesonpage26.
Preprocessingdirectivesalwaysstartwitha//#andoftenhaveoneormorearguments.All
directivesmustnotspanseveralrows.
J2MEPolishsupportsalldirectivesoftheantennapreprocessor(antenna.sourceforge.net),bythe
way.Soifyoumigratefromantenna,youcankeepyourpreprocessingdirectives.

CheckingaSingleSymbolwith#ifdef,#ifndef,#else,#elifdef,#elifndefand#endif
Singlesymbolscanbecheckedeasilywiththe#ifdefdirective:
//#ifdef polish.images.directLoad
Image image = Image.createImage( name );
//# return image;
//#else
scheduleImage( name );
return null;
//#endif
Whenthesymbolpolish.images.directLoadisdefined,thecodewillbetransformedtothe
following:
//#ifdef polish.images.directLoad
Image image = Image.createImage( name );
return image;
//#else
//# scheduleImage( name );
//# return null;
//#endif
If,however,thesymbolpolish.images.directLoadisnotdefined,thetransformationwillbe:
//#ifdef polish.images.directLoad
//# Image image = Image.createImage( name );
//# return image;
//#else
scheduleImage( name );
return null;
//#endif
Each#ifdefand#ifndefdirectiveneedstobeclosedbythe#endifdirective.

78
TheWorldofPreprocessing

Ifavariableisdefined,itcanbecheckedvia//#ifdef [variable]:defined:
//#ifdef polish.ScreenSize:defined

Directive Meaning Explanation


//#ifdef[symbol] if[symbol]isdefined Thesymbolnamed[symbol]needstobe
defined,whenthenextsectionshouldbe
compiled.
//#ifndef[symbol] if[symbol]isnotdefined Thesymbolnamed[symbol]mustnotbe
defined,whenthenextsectionshouldbe
compiled.
//#else else Whentheprevioussectionwasfalse,the
followingsectionwillbecompiled(and
theotherwayround).
//#elifdef[symbol] elseif[symbol]isdefined Thesymbolnamed[symbol]needstobe
definedandtheprevioussectionneedsto
befalse,whenthenextsectionshouldbe
compiled.
//#elifndef[symbol] elseif[symbol]isnotdefined Thesymbolnamed[symbol]mustnotbe
definedandtheprevioussectionneedsto
befalse,whenthenextsectionshouldbe
compiled.
//#endif endoftheifblock Endofeveryifdefandifndefblock.

The#ifdefdirectivescanbenested,ofcourse.Otherpreprocessingdirectivescanbeincludedinto
thesubsectionsaswell:
//#ifdef mySymbol
//#ifndef myOtherSymbol
//#debug
System.out.println("only mySymbol is defined.");
doSomething();
//#else
//#debug
System.out.println("mySymbol and myOtherSymbol are defined.");
doSomethingElse();
//#endif
//#endif

The#ifdefdirectiveanditsrelateddirectivesarefastertoprocessthanthemorecomplex#if
directives.

CheckingSeveralSymbolsandVariableswith#if,#else,#elifand#endif
Witheach#ifdefdirectiveonlyasinglesymbolcanbechecked.Withthe#ifand#elifdirectives,
however,complextermscontainingseveralsymbolsandvariablescanbeevaluated:
//#if useEnhancedInput && (polish.hasPointerEvents || polish.mouseSupported)

79
TheWorldofPreprocessing

doSomething();
//#endif
#ifdirectivescanalsobenestedandcontainotherpreprocessingdirectiveslikethe#ifdefdirectives.
#ifand#ifdefdirectivescanalsobemixed:
//#if !basicInput && (polish.hasPointerEvents || polish.mouseSupported)
doSomething();
//#if polish.BitsPerPixel >= 8
doSomethingColorful();
//#else
doSomethingDull();
//#endif
//#elifdef doWildStuff
doWildStuff();
//#endif

Directive Meaning Explanation


//#if[term] if[term]istrue Thespecifiedtermmustbetrue,whenthe
nextsectionshouldbecompiled.
//#else else Whentheprevioussectionwasfalse,the
followingsectionwillbecompiled(and
theotherwayround).
//#elif[term] elseif[term]istrue Thespecifiedtermneedstobetrueand
theprevioussectionneedstobefalse,
whenthenextsectionshouldbecompiled.
//#endif endoftheifblock Endofeveryifblock.

Inthetermsthebooleanoperators&&,||,^and!canbeused.Complextermscanbeseparated
usingnormalparenthesizes(and).Thetermargumentsforbooleanoperatorsaresymbols,
whicharetruewhentheyaredefinedandfalseotherwise.
Variablescanbecheckedwiththecomparator==,>,<,<=and>=.Argumentsforthecomparators
arevariablesorconstants.
Atermcanincludecomparatorsandbooleanoperators,whenthesectionsareseparatedby
parenthesizes.

BooleanOperator Meaning Explanation


&&orand and Botharguments/symbolsneedtobedefined:
true && true = true
true && false = false && true = false && false = false
||oror or Atleastoneargument/symbolmustbedefined:
true || true = true || false = false || true = true
false || false = false
^orxor exclusive Onlyandatleastoneargument/symbolmustbedefined:
or(xor) true ^ false = false ^ true = true
true ^ true = false ^ false = false

80
TheWorldofPreprocessing

BooleanOperator Meaning Explanation


!ornot not Theargument/symbolmustnotbedefined:
! false = true
! true = false

Comparator Meaning Explanation


== equals Theleftandtherightargumentmustbeequal,integersandstringscan
becompared:
8 == 8 = true
Nokia == Nokia = true
//#if polish.BitsPerPixel == 8
//#if polish.vendor == Nokia
!= notequals Theleftandtherightargumentmustnotbeequal,integersandstrings
canbecompared:
8 != 8 = false
Nokia != Sony-Ericsson = true
//#if polish.BitsPerPixel != 8
//#if polish.vendor != Nokia
> greater Theleftargumentmustbegreaterthantherightone.Onlyintegerscan
becompared:
8 > 8 = false
16 > 8 = true
//#if polish.BitsPerPixel > 8
< smaller Theleftargumentmustbesmallerthantherightone.Onlyintegers
canbecompared:
8 < 8 = false
8 < 16 = true
//#if polish.BitsPerPixel < 8
>= greateror Theleftargumentmustbegreaterthanorequalstherightone.Only
equals integerscanbecompared:
8 >= 8 = true
16 >= 8 = true
//#if polish.BitsPerPixel >= 8
<= smalleror Theleftargumentmustbesmallerthanorequalstherightone.
equals Onlyintegerscanbecompared:
8 <= 8 = true
8 <= 16 = false
//#if polish.BitsPerPixel <= 8

UsingVariableFunctionsforComparingValues
Somevariableshavenotonlydifferentvaluesbutalsostorethemindifferentways.Anexampleare
memoryvaluesliketheHeapSizewhichissometimesdefinedinkilobytesandsometimesin
megabytes.Insuchsituationfunctionscanbeused:
//#if ${ bytes( polish.HeapSize ) } > 102400

Intheaboveexampletheheapsizeiscomparedusingthebytesfunction.Whenafunctionshould
beused,adollarsignandcurlyparenthesizesneedstoembracethecall.Thebytesfunctionwill

81
TheWorldofPreprocessing

return1whenthegivenmemoryvalueisdynamic,soitmightbenecessarytotestforboth
values:
//#if ( ${ bytes( polish.HeapSize ) } > 102400 ) or (polish.HeapSize == dynamic)

Functionscanalsobeusedforfixedvalues:
//#if ${ bytes( polish.HeapSize ) } > ${ bytes( 100 kb ) }

YouwillfindmoreinformationaboutusingfunctionsattheUsingVariablessectiononpage85.

HidingCode
Codesectionscanbetemporarilycommentedout,toavoidproblemsintheIDE.Atypicalproblem
areseveralreturnstatements:
//#ifdef polish.images.directLoad
Image image = Image.createImage( name );
//# return image;
//#else
scheduleImage( name );
return null;
//#endif
Inthisexamplethefirstreturnstatementishiddenwitha//#directive.Whenthefirst#ifdef
directiveistrue,thecorrespondingcodewillbemadevisibleagain.Thespaceafterthe#signis
importantforthecorrecthandlingofsuchcomments.

Debuggingwith#debug,#mdebugand#enddebug
ToincludedebugginginformationinaJ2MEapplicationisnotwithoutproblems.Themain
problemisthatanydebuggingslowsdownanapplicationunnecessarily.Anotherproblemisthat
nobodywantsthedebugginginformationinanapplicationwhichshouldbedeployedinthewild.
WithJ2MEPolishdebuggingstatementscanbeincludedintotheapplicationswithouthavingthe
abovedisadvantages.
The#debugdirectiveisusedtoincludeasinglelineofdebugginginformation:
//#debug
System.out.println("debugging is enabled for this class.");

Youcandefinewhatdebugginglevelisusedbyaddingthedebuggingleveltothe#debugdirective.
Whennolevelisspecifiedthedebuglevelisassumed.
//#debug info
System.out.println("the info debugging level is enabled for this class.");

The#mdebug(multilinedebug)directivecanbeusedtousemultiplelinesofdebugging
information.Itmustbefinishedwiththe#enddebugdirective:
//#mdebug error
e.printStackTrace();
System.out.println("unable to load something: " + e );
//#enddebug

Theaboveexampleactuallyresultsinthesamecodeas:

82
TheWorldofPreprocessing

//#debug error
System.out.println("unable to load something: " + e );

Directive Explanation
//#debug[level] Thenextlineisonlycompiledwhenthedebuggingsettingfortheclassin
whichthedebugginginformationisenabledforthespecifiedlevel.When
nolevelisspecified,thedebuglevelisassumed.
//#mdebug[level] Thenextlinesuptothe#enddebugdirectivewillbecompiledonlywhen
thedebuggingsettingfortheclassinwhichthedebugginginformationis
enabledforthespecifiedlevel.Whennolevelisspecified,thedebug
levelisassumed.Insteadthepreprocessingsymbolspolish.debug.debug,
polish.debug.info,polish.debug.warnetccanbeusedwiththe#ifdef
directive.
//#enddebug Markstheendofthe#mdebugsection.
//#ifdef,//#if Thepreprocessingsymbolspolish.debug.debug,polish.debug.info,
polish.debug.warnetccanbeusedinsteadofthe#mdebugdirective:
//#if polish.debug.info
if (argument == null) {
System.out.println(argument is null!);
}
//#endif

DebugLevels
Followingdebuglevelsarepredefined:
debug,info,warn,errorandfatal.Thespecificlevelforaclasscanbedefinedwiththe
<debug>elementoftheJ2MEPolishtask:
<debug showLogOnError="true" verbose="false" level="error" if="test" >
<filter pattern="com.company.package.*" level="info" />
<filter pattern="com.company.package.MyClass" level="debug" />
</debug>

Pleaseseethesection<debug>inthechapterTheBuildProcessforfurtherinformation.The
levelsareweighted,meaningthatthedebuglevelislowerthantheinfolevel,whichisinturnlower
thantheerrorlevelandsoforth:
debug<info<warn<error<fatal<userdefined
Thuswhentheinfolevelisactivatedforaclass,alldebugginginformationwiththelevelwarn,
error,fatalandwithauserdefinedlevelwillalsobecompiled.
Userspecificdebugginglevelscanbeusefulforaccomplishingspecifictasks.Forexamplealevel
benchmarkcouldbedefinedtoallowthemeasurementoftheperformance:
//#debug benchmark
long startTime = System.currentTimeMilis();
callComplexMethod();
//#debug benchmark

83
TheWorldofPreprocessing

System.out.println("complex method took [" + (System.currentTimeMilis() -


startTime) + "] ms.");

TheDebugUtilityClass
Theutilityclassde.enough.polish.util.Debugcanalsobeuseddirectlyfordebugging.Especiallyits
showLog()methodcanbeusefulinsomecircumstanceswhentheshowLogOnErrorattributeis
notsufficient.
<debug showLogOnError="true" verbose="false" level="error" if="test" >
<filter pattern="com.company.package.*" level="info" />
<filter pattern="com.company.package.MyClass" level="debug" />
</debug>

YoucanmakethedebuginformationavailableinyourMIDletclasswiththefollowingcode:
import de.enough.polish.util.Debug;
public class MyMIDlet extends MIDlet {
//#ifdef polish.debugEnabled
private Command logCmd = new Command( "show log", Command.SCREEN, 10 );
//#endif
private Screen mainScreen;
private Screen display;
[...]
public MyMIDlet() {
[...]
//#ifdef polish.debugEnabled
this.mainScreen.addCommand( this.logCmd );
//#endif
}
public void commandAction(Command cmd, Displayable screen ) {
[...]
//#ifdef polish.debugEnabled
if (cmd == this.logCmd) {
Debug.showLog( this.display );
}
//#endif
}
IntheaboveexampletheMIDletMyMIDletaddsacommandtoitsmainscreenwhenthe
debuggingmodeisenabled.Whenthisisthecase,thepreprocessingsymbol
polish.debugEnabledwillbedefined.Theusercanthenselecttheshowlogcommandtosee
viewallloggingmessages.Whentheuserselectsthereturncommandfromthelogscreen,he
willreturntothescreenwhichhasbeenshownbefore.
Pleasemakesure,thatyouhaveaddedtheimport/enoughj2mepolishclient.jartotheclasspathof
yourproject,whenusingtheDebugclass.
DebugMethod Explanation
Debug.showLog(Displaydisplay) Showsthelogcontainingallmessages.Whenanother
messageisaddedwhilethelogisshown,thelogwillbe
updated.

UsingVariableswith#=
Youcanaddthecontentsofvariableswiththe#=directive:

84
TheWorldofPreprocessing

//#= private String url = "${ start-url }";


Whenthevariableisnotdefined,theaboveexamplewouldthrowanexceptionduringthe
preprocessingstepofthebuildprocess.Youcanusethe[variable]:definedsymbol,whichisset
foreveryknownvariable:
//#ifdef start-url:defined
//#= private String url = "${ start-url }";
//#else
private String url = "http://192.168.101.101";
//#endif

Thisisespeciallyusefulforsettingconfigurationvalues,whichcanchangeeasily,likeWebURLs
andsoon.
ThenameofthevariableneedstobesurroundedbyaDollarSignfollowedbycurlyparenthesizes
(${variable-name}),justlikereferringtoAntpropertiesinthebuild.xml.
Variablescanbedefinedinthe<variables>elementinthebuild.xml.Othervariablesaredefinedin
thedevices.xml,vendors.xmlandgroups.xmlbythecapabilitiesofthedevices,vendorsandgroups.
ThesefilesarelocatedintheinstallationdirectoryofJ2MEPolish.

VariableFunctions

Youcanusefunctionslikeuppercasetochangethevalues.Afunctionisusedwithinthecurly
parenthesizesandsurroundsthevariablenamebynormalparenthesizes:
//#ifdef start-url:defined
//#= private String url = "${ lowercase(start-url) }";
//#else
private String url = "http://192.168.101.101";
//#endif

Whenusingfunctionyoudonotnecessarilyneedavariableyoucanalsouseadirectvalue.This
canbehandywhenhandlingwithmemoryvaluesforexample:
//#if ${ bytes( polish.HeapSize ) } > ${ bytes(100 kb) }

Followingfunctionscanbeused:

Function Explanation
uppercase Translatesthegivenvalueintouppercase.abcbecomesABCforexample.
lowercase Translatesthegivenvalueintolowercase.ABCbecomesabcforexample.
bytes Calculatesthenumberofbytesofthegivenmemoryvalue.1kbbecomes1024
forexample.Thememoryvaluedynamicresultsin1.
kilobytes Calculatesthe(double)numberofkilobytesofthegivenmemoryvalue.Thevalue
willcontainapointanddecimalplaces.512bytesbecomes0.5forexample,
1024bytesbecomes1andsoon.
megabytes Calculatesthe(double)numberofmegabytesofthegivenmemoryvalue.
gigabytes Calculatesthe(double)numberofgigabytesofthegivenmemoryvalue.

85
TheWorldofPreprocessing

SettingCSSStyleswith#style
CSSstylesareusedforthedesignoftheapplication.Thestylesaredefinedinthefilepolish.cssin
theresourcesfolderoftheproject.Thedevelopercancontrolwhichstylesareusedforspecific
Itemsbyusingthe#styledirective:
//#style cool, frosty, default
StringItem url = new StringItem( null, "http://192.168.101.101" );

Intheaboveexampleoneofthestylescool,frostyordefaultisusedforthenewitem.The
stylefrostyisonlyusedwhenthestylecoolisnotdefined.Thestyledefaultisonlyused,
whenneitherthestylecoolnorthestylefrostyisdefined.Thestyledefaultisspecial,sinceit
isalwaysdefined,evenwhenthedesignerdoesnotdefineitexplicitly.The#styledirectiveneedsat
leastonestylenameasargument.Thestyleisdeemedoptionalwhenthestyleendswithaquestion
mark.Inthatcaseitwillonlybeusedwhenitisdefined:
//#style cool?
StringItem url = new StringItem( null, "http://192.168.101.101" );

Thestylesmentionedherecanbedefinedintheresources/polish.cssfile.Inthatfilethenamesof
customstylesneedtostartwithadot.Intheaboveexampleyoucandefinethestyles.cool,
.frostyordefault.Thedefaultstyleisapredefinedstyleanditsnamemustnot,therefore,start
withadot.
Stylesareonlyused,whentheJ2MEPolishGUIisused.Thiscanbetriggeredwiththe
usePolishGuiattributeofthe<build>elementinthebuild.xml.
Using#styledirectiveimprovestheperformanceoftheapplication,sincedynamicstylesneedsome
processingtime.Dynamicstylesdesignitemsbytheirpositioninscreens,seesectionDynamic
Stylesonpage107.
Stylescanbesetforallitemsconstructorsandformanymethods:

InsertionPoint Example Explanation


Itemconstructors //#style cool, frosty, default The#styledirectivecanbe
StringItem url = new StringItem(
null, "http://192.168.101.101" );
placedbeforeanyitem
//#style cool constructor.
ImageItem img = new ImageItem(
null, iconImage,
ImageItem.LAYOUT_DEFAULT, null );
Item. //#style openLink The#styledirectivecanbe
url.setAppearanceMode(
setAppearanceMode Item.HYPERLINK ); placedbeforecallingthe
() setAppearanceModemethodof
anItem.Pleasenote,thatthis
methodisonlyavailablein
J2MEPolish.
List.append() //#style choice The#styledirectivecanbe
list.append( "Start", null );
placedbeforeaddingalist
element.

86
TheWorldofPreprocessing

InsertionPoint Example Explanation


List.insert() //#style choice The#styledirectivecanbe
list.insert( 2, "Start", null );
placedbeforeinsertingalist
element.
List.set() //#style choice The#styledirectivecanbe
list.set( 2, "Start", null );
placedbeforesettingalist
element.
ChoiceGroup.appen //#style choice The#styledirectivecanbe
group.append( "Choice 1", null );
d() placedbeforeaddingan
elementtoaChoiceGroup.
ChoiceGroup.insert( //#style choice The#styledirectivecanbe
group.insert( 2, "Choice 3", null
) );
placedbeforeinsertingan
elementtoaChoiceGroup.
ChoiceGroup.set() //#style choice The#styledirectivecanbe
group.set( 2, "Choice 3", null );
placedbeforesettinganelement
ofaChoiceGroup.
Formconstructor //#style mainScreen Usethe#styledirectivebefore
Form form = new Form( "Menu" );
aFormconstructororbefore
// in subclasses of Form: callingsuper()insubclass
//#style mainScreen constructors.
super( "Menu" );
Listconstructor //#style mainScreen Usethe#styledirectivebefore
List list = new List( "Menu",
List.IMPLICIT );
aListconstructororbefore
callingsuper()insubclass
// in subclasses of List: constructors.
//#style mainScreen
super( "Menu" , List.IMPLICIT );

ExcludeorIncludeCompleteFileswith#condition
The#conditiondirectivecanbeusedtopreventtheusageofcompletefiles,whenaconditionisnot
met:
//#condition polish.usePolishGui

WhenintheaboveexampletheJ2MEPolishGUIisnotused(andthusthesymbol
polish.usePolishGuiisnotdefined),thefilewillnotbeincludedintotheapplicationbundleforthe
currentdevice.Conditionscanusethesameoperatorsandcomparatorslikethe#ifdirective.

DefiningTemporarySymbolsorVariableswith#defineand#undefine
Youcantemporarilydefineandundefinesymbolswiththe#definedirective.Thiscanbeusedto
evaluateacomplexiftermonlyonceandthenreferringasimplesymbolinsteadofusingthe
complextermagain:

87
TheWorldofPreprocessing

//#if !basicInput && (polish.hasPointerEvents || polish.mouseSupported)


//#define tmp.complexInput
//#endif
Youcanlaterjustcheckthetemporarydefinedsymbol:
//#ifdef tmp.complexInput
doSomethingComplex();
//#endif

Directive Explanation
//#define[symbol] Definesthespecifiedsymbol.Youcanneverdefinethesymbolfalse.
//#undefine[symbol] Removesthespecifiedsymbolfromthepoolofdefinedsymbols.Youcan
neverundefinethesymboltrue.

Pleasenotethatyoushouldrelyonadefinedorundefinedsymbolonlyinthesamesourcefile
whereyoudefinedorundefinedthatsymbol.Itisadvisedthatyoustartthenamesofdefined
symbolswithtmp.,sothatyoualwaysknowthatthisisatemporarysymbol.
Youcantemporarilydefineandundefinevariableswiththe#defineaswell.Whentheexpression
afterthe#definedirectivecontainstheequalssign,theleftpartwillbetakenasthevariablename,
andtherightpartasthevariablevalue:
//#if !message:defined
//#define message = Hello world
//#endif
Youcanlaterjustusethedefinedvariablenormally:
//#= String message = ${ message };

Directive Explanation
//#define Definesthespecifiedvariablewiththegivenvalue.
[name]=[value]
//#undefine[name] Removesthespecifiedvariable.

InsertingCodeFragmentswith#include
Youcaninsertcompletecodefragmentswiththe#includedirective:
//#include ${polish.source}/includes/myinclude.java

Withinthefilenameyoucanusealldefinedvariables.Ausefulvariableisespecially
polish.source,whichpointsthebasedirectoryofthefile,whichiscurrentlypreprocessed.Iyou
useonlyrelativenames,pleasebearinmind,thatthebasedirectoryistherootofyourproject(orto
bemoreprecise:thedirectorywhichcontainsthebuild.xmlfile).

AnalyzingthePreprocessingPhasewith#messageand#todo
Sometimesthepreprocessingitselfisrathercomplex.The#messagedirectivecanhelpto

88
TheWorldofPreprocessing

understandtheprocessbyprintingoutmessagesduringthebuildprocess:
//#if !basicInput && (polish.hasPointerEvents || polish.mouseSupported)
//#define tmp.complexInput
//#message complex input is enabled
//#else
//#message complex input is disabled
//#endif

Withineachmessageanyvariablescanbeused.Ifavariableisnotdefined,thevariabledefinition
willbeincludedinthemessage.
//#message using the update-url ${update-url}.
TheaboveexampleresultsinthemessageMESSAGE:usingtheupdateurl
http://update.company.com.beinggivenout,whenthevariableupdateurlhasthevalue
http://update.company.com.Whenthisvariableisnotdefined,themessageMESSAGE:using
theupdateurl${updateurl}.willbeprintedoutinstead.
The#tododirectiveworksverysimilarlikethe#messagedirective,butitaddsthenameofthe
sourcecodeandthelineinwhichthe#tododirectiveisembeddedbeforetheactualmessage(e.g.
TODO:MyMidletline12:ImplementpauseApp()).

HandlingSeveralValuesinVariableswith#foreach
The#foreachdirectivecanbeusedforprocessingavariablewhichhasseveralvaluesseparatedby
comma.Anexampleisthepolish.SoundFormatvariablewhichlistsallsupportedaudio
formatsofadevice,e.g.midi, amr, mp3.
The#foreachdirectivedefinesatemporaryloopvariableandendswiththe#next[loopvarname]
directive:
//#foreach [loop-var-name] in [variable-name]
...[any directives and code]...
//#next [loop-var-name]

Thefollowingexampleillustratesthis:
String format;
//#foreach format in polish.SoundFormat
format = "${ lowercase( format ) }";
System.out.println( "The audio-format " + format + " is supported by this
device." );
//#next format

Youcanuseanynumberandanykindofcodeandpreprocessingdirectiveswithinthe#foreachloop
itself.Soyoucanevenusenested#foreachloops,forexample.Thecodefragmentwithinthe
#foreachloopwillbecopiedintothepreprocessedsourcecodeasmanytimeastherearevalues.In
theaboveexampleitwouldbecopiedthreetimes,sinceintheexamplethreeformatsaresupported.
Thiscopyingprocesshastwoimplications:
1. Anyvariablesshouldbedefinedoutsideoftheloop(buttheycanbesetandusedwithinthe
loop,ofcourse),and

89
TheWorldofPreprocessing

2. Whentheapplicationisdebuggedorcompiled,breakpointsorerrorscanpointtothewrong
sourcecodelines.
Ifyoukeeptheseimplicationsinmindyouhaveanotherpowerfuldirectiveatyourhand.

UsefulSymbols

APIsandMIDPVersion
PleaserefertothesectionCapabilitiesinthechapterTheDeviceDatabaseforstandard
preprocessingsymbols.
ForeachAPIthedevicesupportsacorrespondingsymbolpolish.api.[name]isdefined:
polish.api.mmapi whentheMobileMediaAPIissupported,or
polish.api.nokia-ui whenthedevicesupportstheNokiaUIAPI.

WhenthedevicesupportstheMIDP/2.0platform,thesymbolpolish.midp2isdefined,
otherwisethesymbolpolish.midp1.
WhenadevicesupportstheCLDC/1.0standard,thesymbolpolish.cldc1.0isdefined.When
theCLDC/1.0standardissupported,thesymbolpolish.cldc1.1isdefinedinstead.

J2MEPolishSymbols
Dependingonthesettingsinthebuild.xmldifferentsymbolswillbedefined.Pleasecomparethe
TheBuildSection,page36.
polish.usePolishGui isdefinedwhentheGUIofJ2MEPolishisusedforthecurrentdevice.
polish.debugEnabled isdefinedwhentheloggingofmessagesandthedebugmodeis
enabled.
polish.debugVerbose isdefinedwhenthedebugmodeisenabledandissettoverbose.
Whentheverbosemodeisenabled,thrownexceptionsshouldcontainadetailedmessage.
polish.skipArgumentCheck canbedefinedinthesymbolsattributeofthe<build>element
withinthebuild.xmlfile.Whenthissymbolisdefined,allGUIclassesofJ2MEPolishwillnot
checktheinputvariables.Thisisusefulforminimizingthememoryfootprintwhenan
applicationisstable.

UsefulVariables
PleaserefertothesectionCapabilitiesonpage26forstandardpreprocessingvariables.
Othervariablesinclude:
polish.animationIntervaldefinestheintervalinmillisecondsforanimations.Thisdefaults
to100ms,butyoucanchangethisvaluewithinthe<variables>elementofthe<build>section.
polish.classes.fullscreendefinesthenameofthefullscreenclass,whenthedevice
supportssuchaclass.FordeviceswhichsupporttheNokiaUIAPIthisvariablecontains
com.nokia.mid.ui.FullCanvas.Followingexampleillustratestheusage:
public abstract class MyCanvas
//#if polish.useFullScreen && polish.classes.fullscreen:defined

90
TheWorldofPreprocessing

//#define tmp.fullScreen
//#= extends ${polish.classes.fullscreen}
//#else
extends Canvas
//#endif

polish.Vendordefinesthevendorofthecurrentdevice,e.g.SiemensorNokia:
//#if polish.Vendor == Nokia

polish.Identifierdefinestheidentifierofthecurrentdevice,e.g.Nokia/6600.

polish.classes.midlet-1definesthefirstMIDletofthecurrentsuite.

polish.classes.midlet-2definesthesecondMIDletofthecurrentsuite,ifthereisany.

polish.classes.midlet-ndefinesthenthMIDletofthecurrentsuite,ifthereisany.

FileOperations
Thevariablepolish.sourcepointsthecurrentsourcedirectory.Thisisusefulfor//#include
directives.

91
TheJ2MEPolishGUI

TheJ2MEPolishGUI
Overview
TheJ2MEPolishGUI4providesaverypowerfulandefficientwaytodesigntheuserinterfaceof
wirelessJavaapplications.Ithasseveraluniquefeatureswhicheasetheusagesignificantly:
TheJ2MEPolishGUIiscompatiblewiththestandardMIDPGUI,sotheprogrammerdoesnot
needtolearnanewAPI.
ThenecessarycodeisweavedintotheapplicationautomaticallybyJ2MEPolish,sothatno
specificimportstatementsneedtobeusedandthatevenexistingapplicationscanusetheGUI
withoutanymodifications.
TheGUIisdesignedusingsimpletextfiles,whichresideoutsideoftheactualapplicationsource
code.ThewebstandardCSS5isusedforthedesign,sothatwebdesignerscannowworkonthe
designofJ2MEapplicationswithoutthehelpofprogrammers,whiletheprogrammerscan
concentrateonthebusinesslogic.Alsothedesigncanbechangedatanytimewithoutchanging
thesourcecode.
Alldesignscanbeadjustedeasilytodifferentdevices,vendors,devicegroupsorevenlocales.
AllelementsoftheMIDP/2.0GUIaresupportedevenonMIDP/1.0devices.SoMIDP/2.0
specificitemslikeaPOPUP ChoiceGrouporaCustomItemcanbeusedonMIDP/1.0phonesas
well.
ThedrawbackoftheJ2MEPolishGUIistheincreasedsizeoftheapplicationpackage.Youshould
calculateupto30kbadditionalspacefortheGUI,dependingonwhatGUIelementsandwhat
designsareused.Moderndevices
likeSymbianbaseddevices(Nokia,
Siemensandmanyothervendors)
supportapplicationsizesupto
severalmegabytes,sotheadditional
sizeismostoftennoproblem.The
situationis,however,differenton
someolderdeviceslikeNokia'sold
Series40models,whichonly
acceptedapplicationswithasizeof
upto64kb.Forsuchdevicesthe
GUIisusuallynotusedevenwhen
theGUIisactivated,unlesstheusage
isforced.
Fig.3:Anexampledesignofa Fig.4:Thesameapplicationwith
normalListScreen. anotherdesign.Thebackgroundis
actuallyanimated:itstartswhite
andditherstotheshownpink. ActivationoftheGUI
TheGUIcanbeactivatedbythesettingtheusePolishGuiattributeofthe<build>elementinthe

4 GUIstandsforGraphicalUserInterface
5 CSS:CascadingStyleSheets

92
TheJ2MEPolishGUI

build.xmlfile.J2MEPolishwillthenweavethenecessarycodeautomaticallyintotheapplication.

Theattributeacceptsthevaluesyes/true,no/falseandalways.Whentrueoryesis
given,theGUIwillbeused,unlessatargetdevicehasnottherecommendedcapabilities(i.e.a
maximumJARsizeabove100kbandatleastacolordepthof8bitspercolor).Forsuchdevicesthe
normalMIDPGUIisthenused.Whentheattributeissettoalways,theGUIwillbeusedforall
targetdevices,evenwhentheydonothavetherecommendedcapabilities.
ThefollowingexampleactivatestheGUIformostdevices:
<build
usePolishGui="true"
[...]

AlternativelyyoucanenabletheJ2MEPolishGUIbydefiningthepreprocessingvariable
polish.usePolishGui.ThisisusefuliftheGUIshouldbeactivatedforselecteddevicesonly.The
followingexampleactivatedtheGUIonlyforNokia/Series60devices:
<build
symbols="showSplash, AnotherExampleSymbol"
fullscreen="menu"
usePolishGui="false"
>
<!-- activate the GUI for Nokia/Series devices -->
<variables>
<variable name="polish.usePolishGui"
value="true"
if="polish.group.Series60" />
</variables>
[...]
</build>

ConfiguringtheJ2MEPolishGUI
TheGUIcanbeconfiguredquiteextensivelybymodifyingthebuild.xmlfile.

UsingtheGUIinFullScreenMode

TheJ2MEPolishGUIcanusethecompletescreenonMIDP/2.0devicesaswellasonMIDP/1.0
deviceswhichprovideproprietarymethodsforusingafullscreenmode.
Thefullscreenmodecanbeactivatedwiththefullscreenattributeofthe<build>element:
<build
usePolishGui="true"
fullscreen="menu"
[...]
Theattributecanhavethevaluesyes/true,no/falseormenu.Whencommandsareused
bytheapplication,themenumodeneedstobeused.Inthatcasethemenubarwillberendered
byJ2MEPolishandthemenucanbedesignedwithCSS(e.g.bysettingthemenubar-color
attributeorusingthemenustyle).
Alternativelythepolish.FullScreenpreprocessingvariablecanbeset,whichacceptsthesame
valuesasthethefullscreenattribute.Thiscanbeusedforafinegrainedcontrol.Siemens
devicesdoacceptcommandseveninthenormalfullscreenmode,sothereisnoneedtousethe

93
TheJ2MEPolishGUI

menumodeforsuchdevices:
<build
usePolishGui="true"
fullscreen="menu"
>
<variables>
<variable
name="polish.FullScreen"
value="yes"
if="polish.vendor == Siemens"
/>
<variables>
[...]

Fig.1:The"menu"andthenormalfullscreenmodeontheSiemensCX65

SomeMIDP/2.0devicesdonotsupportthemenumode,sincetheydonotforwardkeyevents
whenasoftkeyispressed.J2MEPolishdetermineswhetheradevicesupportsthemenumodeby
evaluatingthedevicedatabase.WhenthehasCommandKeyEventsfeatureisset,thedevice
supportsthepureMIDP/2.0menumode.Additionallythecapabilitieskey.LeftSoftKeyand
key.RightSoftKeycanbesettodefinethekeycodesforthesoftkeys(thesearethevalues,
whicharereportedtothekeyPressedmethodofaCanvas).Whennokeysaredefined,thevalue
6isassumedfortheleftsoftkey,andthevalue7fortherightsoftkey.
<device
supportsPolishGui="true">
<identifier>Siemens/CX65</identifier>
<features>hasCommandKeyEvents</features>
<capability name="ScreenSize" value="132x176"/>
<capability name="key.LeftSoftKey" value="-1" />
<capability name="key.RightSoftKey" value="-4" />
</device>

94
TheJ2MEPolishGUI

ConfiguringCommands,LabelsandProgrammingoftheGUI
PreprocessingvariablesandsymbolscanbeusedforchangingtheappearanceorlogicoftheJ2ME
PolishGUI.

PreprocessingSymbol Explanation
polish.skipArgumentCheck Whenthissymbolisdefined,methodargumentswillnotbechecked.
Thisimprovestheruntimeperformanceandthesizeofthe
applicationabit.

PreprocessingVariable Default Explanation


polish.animationInterval 100 Definestheintervalinmillisecondsfor
animations.Thisdefaultsto100ms.
polish.classes.ImageLoader UsuallyJ2MEPolishloadsallimagesfromthe
JARfileusingtheImage.createImage( String
url ) method.Thisworksfineformost
situations,butsometimesimagesshouldbe
retrievedfromtheRMSortheinternet.Insuch
casesyoucandefinethe
polish.classes.ImageLoadervariable.Thegiven
class(orstaticfieldofaclass)needstoimplement
thejavax.microedition.lcdui.Image
loadImage( String url )throws
IOExceptionmethod,whichisresponsiblefor
retrievingtheimage.
polish.ChoiceGroup.suppres false AmultipleListorChoiceGroupaddsthe
sMarkCommands commandsMarkandUnmarkbydefaulttothe
menu.Thenamesofthecommandscanbe
changedeasily,comparepage76.Ifyouwantto
suppressthecommandscompletely,the
polish.ChoiceGroup.suppressMarkCommands
variablehastobesettotrue.
polish.ChoiceGroup.suppres false AnimplicitorpopupChoiceGrouporListdo
sSelectCommand usuallyhaveaSelectcommandwhichalsocan
bedeactivated.
polish.TextField.suppressCo false ATextFieldandTextBoxdocontaintheDelete
mmands aswellastheClearcommandsbydefault.
polish.command.ok OK ThelabelfortheOKmenuitem,whichisused
Screenmenuswhenthemenufullscreenmode
isused.
polish.command.cancel Cancel ThelabelfortheCancelmenuitem.
polish.command.select Select ThelabelfortheSelectmenuitem,whichisused

95
TheJ2MEPolishGUI

PreprocessingVariable Default Explanation


byanimplicitorexclusiveListorChoiceGroup.
polish.command.mark Mark ThelabelfortheMarkmenuitemofamultiple
ListorChoiceGroup.
polish.command.unmark Unmark ThelabelfortheUnmarkmenuitemofamultiple
ListorChoiceGroup.
polish.command.options Options Thelabelforthemenuwhenseveralmenuitems
areavailable.
polish.command.delete Delete ThelabelfortheDeletemenuitem,whichisused
byTextFields.
polish.command.clear Clear ThelabelfortheClearmenuitem,whichisused
byTextFields.
polish.title.input Input ThetitleofthenativeTextBoxwhichisusedfor
theactualinputoftext.Thistitleisonlyused,
whenthecorrespondingTextFielditemhasno
label.WhentheTextFieldhasalabel,thatlabelis
usedasatitleinstead.
polish.usePolishGui CanbeusedforactivatingthePolishGUIonlyfor
selecteddevices.
polish.FullScreen Canbeusedforselectivelyactivatingthe
FullScreenmode.Possiblevaluesaretrue,
falseormenu.

Thefollowingexampledemonstratessomeconfigurationoptions:
<!-- symbol: don't check method-parameters: -->
<build
usePolishGui="true"
fullscreen="menu"
symbols="polish.skipArgumentCheck"
>
<variables>
<!-- suppress Mark/Unmark commands for ChoiceGroups and Lists: -->
<variable name="polish.ChoiceGroup.suppressMarkCommands"
value="true" />
<!-- suppress Delete/Clear commands for TextBoxes and TextFields: -->
<variable name="polish.TextField.suppressCommands"
value="true" />
<!-- use own image loader implementation: -->
<variable name="polish.classes.ImageLoader"
value="com.company.j2me.ImageLoader" />
<variables>
[...]

TheJ2MEPolishGUIforProgrammers
UsingtheJ2MEPolishGUIisquitesimpleactually.SincetheJ2MEPolishGUIiscompatiblewith

96
TheJ2MEPolishGUI

theMIDPstandard,neitherimportstatementsnortheactualcodeneedstobechanged.

SettingStyles
Youshouldusethe#stylepreprocessingdirectiveforapplyingthedesireddesignstyles.This
directivecanbeusedinfrontofanyItemconstructorandbeforesomeothermethods:
InsertionPoint Example Explanation
Itemconstructors //#style cool, frosty, default The#styledirectivecanbe
StringItem url = new StringItem(
null, "http://192.168.101.101" );
placedbeforeanyitem
//#style cool constructor.
ImageItem img = new ImageItem(
null, iconImage,
ImageItem.LAYOUT_DEFAULT, null );
Item. //#style openLink The#styledirectivecanbe
url.setAppearanceMode(
setAppearanceMode Item.HYPERLINK ); placedbeforecallingthe
() setAppearanceModemethodof
anItem.Pleasenote,thatthis
methodisonlyavailablein
J2MEPolish.
List.append() //#style choice The#styledirectivecanbe
list.append( "Start", null );
placedbeforeaddingalist
element.
List.insert() //#style choice The#styledirectivecanbe
list.insert( 2, "Start", null );
placedbeforeinsertingalist
element.
List.set() //#style choice The#styledirectivecanbe
list.set( 2, "Start", null );
placedbeforesettingalist
element.
ChoiceGroup.appen //#style choice The#styledirectivecanbe
group.append( "Choice 1", null );
d() placedbeforeaddingan
elementtoaChoiceGroup.
ChoiceGroup.insert( //#style choice The#styledirectivecanbe
group.insert( 2, "Choice 3", null
) );
placedbeforeinsertingan
elementtoaChoiceGroup.
ChoiceGroup.set() //#style choice The#styledirectivecanbe
group.set( 2, "Choice 3", null );
placedbeforesettinganelement
ofaChoiceGroup.
Formconstructor //#style mainScreen Usethe#styledirectivebefore
Form form = new Form( "Menu" );
aFormconstructororbefore
// in subclasses of Form: callingsuper()insubclass
//#style mainScreen constructors.
super( "Menu" );

97
TheJ2MEPolishGUI

InsertionPoint Example Explanation


Listconstructor //#style mainScreen Usethe#styledirectivebefore
List list = new List( "Menu",
List.IMPLICIT );
aListconstructororbefore
callingsuper()insubclass
// in subclasses of List: constructors.
//#style mainScreen
super( "Menu" , List.IMPLICIT );

Thefollowingexampleusesthe.mainMenustyleforthedesignoftheform:
import javax.microedition.lcdui.Form;
public class MainMenu extends Form {
public MainMenu( String title ) {
//#style mainMenu
super( title );
...
}
}

The.mainMenustylethenneedstobedefinedwithintheresources/polish.cssfile,e.g.:
.mainMenu {
background-image: url( bg.png );
columns: 2;
}

Youcanalsouseseveralstylenamesina#styledirective.Inthiscasethefirstfounddirectiveis
used:
import javax.microedition.lcdui.Form;
public class MainMenu extends Form {
public MainMenu( String title ) {
//#style mainMenu, screen
super( title );
...
}
}

Whennoneoftheprovidedstyledefinitionsisfound,thebuildwillreportthiserrorandabortthe
processing.

UsingDynamicandPredefinedStyles
Whendynamicstylesareused,youdonotevenhavetosetthe#styledirectives.Inthiscasethe
designsdodependontheclasses.AllFormsaredesignedwiththeformstyleforexample.Using
dynamicstylescanbeafastwaytocheckouttheGUIforexistingapplications,butthisrequires
additionalmemoryandruntime.Youshould,therefore,usenormalstaticstylesforthefinal
application.
Predefinedstylesareusedbydefaultforsomeelements.Soisthetitlestyleresponsibleforthe
appearanceofScreentitlesforexample.
Pleaserefertothedocumentationonpage105formoreinformationonstatic,dynamicand

98
TheJ2MEPolishGUI

predefinedstyles.

PortingMIDP/2.0ApplicationstoMIDP/1.0Platforms
WhenyouusetheJ2MEPolishGUIyoucanuseMIDP/2.0 UsefulPreprocessingSymbols
widgetslikeaPOPUP ChoiceGrouporaCustomItemon polish.midp1 /
MIDP/1.0devicesaswellwithoutanyrestrictions. polish.midp2indicatesthe
currentMIDPplatform.
SourcecodeadjustmentsareonlynecessarywhenMIDP/2.0 polish.cldc1.0 /
onlyfeaturesareused,whichareoutsideofthescopeofthe polish.cldc1.1indicatesthe
J2MEPolishGUI,e.g.Display.flashBacklight(int). currentconfiguration.

TheMIDP/2.0callDisplay.setCurrentItem(Item)issupported polish.usePolishGuiis
enabledwhentheGUIofJ2ME
bytheJ2MEPolishGUIforbothMIDP/2.0aswellas Polishisused.
MIDP/1.0devices.
polish.api.mmapiisdefined
Whenaspecificcallisnotsupportedbyatargetdevice,the whentheMobileMediaAPIis
buildprocesswillbeabortedwithacompileerror.Usuallythat supportedbythecurrentdevice.
errorthenneedstobesurroundedbyanappropriate#if polish.api.nokia-uiis
preprocessingdirective,e.g.: definedwhentheNokiaUIAPI
issupportedbythecurrent
//#ifdef polish.midp2 device.
this.display.flashBacklight( 1000 );
//#endif

PleasehavealookatthechapterUsingCustomItemsonpage161formoreinformationon
customitems.

ProgrammingSpecificItemsandScreens
IngeneraltheJ2MEPolishGUIisfullycompatibletotheMIDP/2.0UIstandard.Thereare,
howeversomeenhancementthatarenotavailableintheMIDP/2.0standard.

ProgrammingtheTabbedForm
TheTabbedFormisaformthatseparatestheincludedGUIelementsonseveraltabs.Youcanuse
anyFormmethodslikesetItemStateListener(..)intheTabbedForm.Theimplementationoffers
someadditionalmethodsforconfiguringitstabs:
directivecanbeusedinfrontofanyItemconstructorandbeforesomeothermethods:
Method Example Explanation
TabbedForm(String //#style myTabbedForm CreatesanewTabbedForm.
TabbedForm form = new TabbedForm(
title,String[] "Hello", new String[] {"First
tabNames,Image[] Tab", "another tab"}, null );
tabImages)
append(int form.append( 2, myStringItem ); Addstheitemtothespecified
tabIndex,Itemitem) tab.Thefirsttabhasgotthe
index0.
set(inttabIndex,int form.set( 2, 1, myStringItem ); Setstheitemtothespecified

99
TheJ2MEPolishGUI

Method Example Explanation


itemIndex,Itemitem indexonthegiventab.
)
delete(inttabIndex, form.delete( 2, myStringItem ); Deletesthegivenitemfromthe
Itemitem) specifiedtab.

ThefollowinglistingdemonstratestheusageoftheTabbedForm:

package de.enough.polish.demo;

import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemStateListener;

import de.enough.polish.ui.TabbedForm;

public class TabbedFormDemo implements ItemStateListener {

private TextField nameField;

public TabbedFormDemo( DemoMidlet midlet, Display display, Command


returnCmd ) {
String[] tabNames = new String[]{ "Input", "Choice", "Connection",
"Test", "Settings", "Internet" };
//#style tabbedScreen
TabbedForm form = new TabbedForm("TabbedDemo", tabNames, null );
//#style label
StringItem label = new StringItem( null, "name:" );
form.append( 0, label );
//#style input
this.nameField = new TextField( null, "Robert", 30, TextField.ANY |
TextField.INITIAL_CAPS_WORD );
form.append(0, this.nameField);
//#style label
label = new StringItem( null, "birthday:" );
form.append( 0, label );
//#style input
DateField birthdate = new DateField( null, DateField.DATE );
form.append( 0, birthdate );

//#style label
label = new StringItem(null, "What kind of animals do you like:");
form.append( 1, label );
//#style multipleChoice
ChoiceGroup choice = new ChoiceGroup( null, Choice.MULTIPLE );
//#style choiceItem
choice.append("dogs", null);

100
TheJ2MEPolishGUI

//#style choiceItem
choice.append("cats", null);
//#style choiceItem
choice.append("birds", null);
form.append(1, choice);

//#style label
label = new StringItem(null, "Connection:");
form.append( 2, label );
//#style multipleChoice
choice = new ChoiceGroup( null, Choice.MULTIPLE );
//#style choiceItem
choice.append("ISDN", null);
//#style choiceItem
choice.append("DSL", null);
//#style choiceItem
choice.append("Cable", null);
form.append(2, choice);

form.addCommand(returnCmd);
form.setCommandListener(midlet);
form.setItemStateListener( this );
display.setCurrentItem( choice );
}

public void itemStateChanged(Item item) {


if (item instanceof TextField) {
TextField field = (TextField) item;
System.out.println("Item State Changed: " +
field.getString() );
} else {
System.out.println("Item State Changed: " + item );
}
}
}

101
TheJ2MEPolishGUI

TheJ2MEPolishGUIforDesigners
J2MEPolishincludesanoptionalGraphicalUserInterface,whichcanbedesignedusingtheweb
standardCascadingStyleSheets(CSS).Soeverywebdesignercannowdesignmobileapplications
thankstoJ2MEPolish!Thischapterwillexplainalldetailsofthedesignpossibilities,noprior
knowledgeaboutCSSisrequired.6TheGUIiscompatiblewiththejavax.microedition.uiclasses,
thereforenochangesneedtobemadeinthesourcecodeoftheapplication.TheGUIwillbe
incorporatedbythepreprocessingmechanismautomatically,unlesstheusePolishGuiattributeof
the<build>elementissettofalseinthebuild.xmlfile.

AQuickGlance
Alldesignsettingsandfilesarestoredintheresourcesdirectoryoftheproject,unlessanother
directoryhasbeenspecified.7Themostimportantfileispolish.cssinthatdirectory.Alldesign
definitionscanbefoundhere.Thedesigndefinitionsaregroupedinstyles.Astylecanbe
assignedtoanyGUIitemlikeatitle,aparagraphoraninputfield.Withinastyleseveralattributes
anditsvaluesaredefined:
.myStyle {
font-color: white;
font-style: bold;
font-size: large;
font-face: proportional;
background-color: black;
}
InthisexamplethestylecalledmyStyledefinessomefontvaluesandthecolorofthebackground.
Anystylecontainsaselectoraswellasanumberofattributesanditsvalues:

.myStyle { font-color: white; }

selector/nameattribute value
Fig.2:Structureofastyle

Eachattributevaluepairneedstobefinishedwithasemicolon.Thestyledeclarationneedstobe
finishedbyaclosingcurvedparenthesis.Theselectorornameofstyleiscaseinsensitive,so
.MySTYleisthesameas.myStyle.
Apartfromthepolish.cssfile,youcanputimagesandothercontentsintotheresourcesfolder.
Subfoldersareusedforstylesandcontentforspecificdevicesandgroups.Youcanputallresources
forNokiadevicesintotheNokiafolderandresourcesforSamsung'sE700intothe
Samsung/E700folder.ThisisdescribedinmoredetailintheDesigningSpecificDevicesand
DeviceGroupssection.
YoucanspecifystylesdirectlyforGUIitemswiththe#stylepreprocessingdirectiveinthesource
code.AlternativelyyoucanusethedynamicnamesoftheGUIitems,e.g.pfortextitems,afor
hyperlinksorformpforalltextitemswhichareembeddedinaform.Thepossiblecombinations
aswellasthepredefinedstylenamesarediscussedinthesectionDynamic,StaticandPredefined

6 Refertohttp://www.w3schools.com/css/foranexcellenttutorialofCSSforwebpages.
7 YoucanspecifythedirectorywiththeresDirattributeofthe<build>elementinthebuild.xmlfile.Thiscanbe
usedtocreatecompletelydifferentdesignsforoneapplication.

102
TheJ2MEPolishGUI

Styles.
Stylescanextendotherstyleswiththeextendskeyword,e.g..myStyleextendsbaseStyle{}.This
processisdescribedinthesectionExtendingStyles.
J2MEPolishsupportstheCSSboxmodelwithmargins,paddingsandcontent.Othercommon
designsettingsincludethebackground,theborderandfontsettings.Thesecommonsettingsare
describedinthesectionCommonDesignAttributes.AttributesforspecificGUIitemsaswellas
thedetailsofthedifferentbackgroundandbordertypesarediscussedinthesectionSpecific
DesignAttributes.

DesigningforSpecificDevicesor
DeviceGroups

Sometimesthedesignneedstobeadaptedtoaspecificdeviceoragroupofdevices.Youcaneasily
usespecificpictures,stylesetceterabyusingtheappropriatesubfoldersoftheresourcesfolder.

TheHierarchyoftheresourcesFolder
Intheresourcesfolderitselfyouputallresourcesanddesigndefinitionswhichshouldbevalidfor
alldevices.Theresourceswillcopiedintotherootfolderoftheapplication.
Inthefoldernamedlikethevendorofadevice(e.g.Nokia,SamsungorMotorola)youputall
resourcesanddesigndefinitionsfordevicesofthatvendor.
Inthefoldernamedliketheexplicitandimplicitgroupsofadeviceyouaddtheresourcesand
designdefinitionsforthesedevicegroups.AnexplicitgroupisforexampletheSeries60group,
implicitgroupsaredefinedbythesupportedAPIsofadeviceandtheBitsPerPixelcapabilityof
devices.YoucanaddasmallmovieforalldeviceswhichsupporttheMobileMediaAPI(mmapi)
byputtingthatmovieintotheresources/mmapifolder.Oryoucanaddcoloredimagesforall
deviceswhichhaveatleastacolordepthof8bitsperpixelbyputtingtheseimagesintothe
resources/BitsPerPixel8+folder.
Lastbutnotleastyoucanusedevicespecificresourcesanddesigndefinitionsbyputtingtheminto
theresources/[vendor]/[device]folder,e.g.resources/Nokia/6600or
resources/Samsung/E700.
Anyexistingresourceswillbeoverwrittenbymorespecificresources:
1. Atfirstthebasicresourcesanddefinitionsfoundintheresourcesfolderwillbeused.
2. Secondlythevendorspecificresourceswillbeused,e.g.resources/Nokia.
3. Thirdlythegroupspecificresourceswillbeused,e.g.resources/mmapi,resources/Series60,
resources/BitsPerPixel.8+orresources/BitsPerPixe.16.
4. Theresourcesandsettingsinthedevicespecificfolderwilloverwriteallotherresourcesand
settings.Thedevicespecificfolderisforexamplethefolderresources/Nokia/6600forthe
Nokia/6600phoneorthefolderresources/Samsung/E700forSamsung'sE700.
Whenyouaddthepolish.cssfileforaspecificvendor,groupordevice,youdonotneedtorepeatall
stylesandattributesfromthemorebasicsettings.Youneedtospecifythemorespecificsetting
only.Whenyouwanttochangethecolorofafont,youjustneedtospecifythefontcolor
attributeofthatstyle.Nootherattributesorstylesneedtobedefined.Thisisthecascading

103
TheJ2MEPolishGUI

characteroftheCascadingStyleSheetsofJ2MEPolish.
Thisexampleillustratesthecascadingcharacterofpolish.css:
Inresources/polish.cssyoudefinethestylemyStyle:
.myStyle {
font-color: white;
font-style: bold;
font-size: large;
font-face: proportional;
background-color: black;
}
YoucanchangethefontcolorofthatstyleforallNokiadeviceswiththefollowingdeclarationin
resources/Nokia/polish.css:
.myStyle {
font-color: gray;
}
YoucanspecifyanotherfontsizeandfontcolorfortheNokia6600phonewiththesesettingsin
resources/Nokia/6600/polish.css:
.myStyle {
font-color: red;
font-size: medium;
}

Groups
Everydevicecanhaveexplicitandimplicitgroups.Explicitgroupsarestatedbythe<groups>
elementofthedeviceinthefiledevices.xml8.Implicitgroupsaredefinedbythecapabilitiesofthe
device:EachsupportedAPIresultsinanimplicitgroupandtheBitsPerPixelcapabilityresultsin
severalgroups.

APIandJavaPlatformGroups

AdevicecansupportdifferentAPIsandJavaplatforms.
WhenthedevicesupportstheMIDP/1.0standard,itbelongstothemidp1group,otherwiseit
belongstothemidp2group.SoyoucanspecifythelayoutofMIDP/1.0devicesin
resources/midp1/polish.css.AndyoucanusespecificimagesorotherresourcesforMIDP/2.0
devicesinthefolderresources/midp2.Thesupportedplatformofadevicecanbespecifiedinthe
devices.xmlfilewiththe<JavaPlatform>element.Alternativelythissettingcanbespecifiedinthe
filegroups.xmlforspecificgroups.
ForeachsupportedAPIanimplicitgroupiscreated.WhenthedevicesupportstheMobileMedia
API(mmapi),itbelongstothemmapigroup.WhenthedevicesupportstheNokiaUIAPI,it
belongstothenokiauigroup.Thenameoftheimplicitgroupisdefinedbythe<symbol>
elementoftheAPIinthefileapis.xml.

BitsPerPixelGroups

EverydevicedisplayhasaspecificcolordepthwhichisspecifiedbytheBitsPerPixelcapabilityof
thatdeviceinthedevices.xmlfile.Dependingonhowmanybitsperpixelaresupported,thedevice

8 devices.xmlcaneitherbefoundintherootfolderoftheprojectorintheimport/enoughj2mepolishbuild.jarfile.

104
TheJ2MEPolishGUI

belongstodifferentgroups:

BitsperPixel Colors Groups


1 21=2(b/w) BitsPerPixel.1
4 24=16 BitsPerPixel.4
BitsPerPixel.4+
8 28=256 BitsPerPixel.8
BitsPerPixel.8+
BitsPerPixel.4+
12 212=4.096 BitsPerPixel.12
BitsPerPixel.12+
BitsPerPixel.8+
BitsPerPixel.4+
16 216=65.536 BitsPerPixel.16
BitsPerPixel.16+
BitsPerPixel.12+
BitsPerPixel.8+
BitsPerPixel.4+
18 218=262.144 BitsPerPixel.18
BitsPerPixel.18+
BitsPerPixel.16+
BitsPerPixel.12+
BitsPerPixel.8+
BitsPerPixel.4+
24 224=16.777.216 BitsPerPixel.24
BitsPerPixel.24+
BitsPerPixel.18+
BitsPerPixel.16+
BitsPerPixel.12+
BitsPerPixel.8+
BitsPerPixel.4+

Soyoucanputimagesforphoneswithatleast16colorsintotheresources/BitsPerPixel.4+folder.
Andyoucanspecifysettingsfortruecolordevicesinthefile
resources/BitsPerPixel.24/polish.css.

Dynamic,StaticandPredefinedStyles

J2MEPolishdistinguishesbetweendynamic,staticandpredefinedstyles:
PredefinedstylesareusedbytheGUIforseveralitemslikescreentitles.
Staticstylesaredefinedinthesourcecodeoftheapplicationwiththe#stylepreprocessing
directive.

105
TheJ2MEPolishGUI

Dynamicstylesareusedforitemsaccordingtotheirpositiononthescreen.

StaticStyles
Theeasieststylesarethestaticones.Theprogrammerjustneedstotellthedesignerthestylenames
andwhattheyareusedfor(thatisforwhatkindofitemsorscreens)andthedesignerdefinesthem
intheappropriatepolish.cssfile.Staticstylesalwaysstartwithadot,e.g..myStyle.
Staticstylesarefasterthandynamicstyles.Itisthereforerecommendedtousestaticstyleswhenever
possible.

PredefinedStyles
PredefinedstylesarestaticstyleswhichareusedbytheJ2MEPolishGUI.Incontrasttothenormal
userdefinedstaticstylestheirnamesdonotstartwithadot,e.g.titleinsteadof.title.
Followingpredefinedstylesareused:

Style Description
title Thestyleofscreentitles.ForMIDP/2.0devicesthenative
implementationisusedbydefault,unlessthepreprocessingvariable
polish.usePolishTitleisdefinedwithtrue:
<variable name="polish.usePolishTitle" value="true"
unless="polish.Vendor == Nokia" />

YoucanalsousecustomstylesforspecificScreensorChoiceGroupsby
usingthetitlestyleattribute(comparepage131).
focused Thestyleofacurrentlyfocuseditem.ThisstyleisusedinLists,Forms
andforContainersliketheChoiceGroup.Youcanalsousecustom
stylesforspecificScreensorChoiceGroupsbyusingthefocused
styleattribute(comparepage131).
menu Thisstyleisusedfordesigningthemenubarinthefullscreenmode.
ThefullscreenmodecanbetriggeredbythefullScreenModeattribute
ofthe<build>elementinthebuild.xml(with
fullScreenMode=menu).Inthemenustyleyoucanalsodefinewhich
styleisusedforthecurrentlyfocusedcommandwiththefocused
styleattribute,e.g.focusedstyle:menuFocused;.Inthiscaseyou
needtodefinethestaticstyle.menuFocusedaswell.
menuItem Thestyleusedforthemenuitems(thecommands)ofascreen.When
menuItemisnotdefined,themenustyleisusedinstead.
label Thisstyleisusedforthemenuthelabelofanyitem.Onecanspecify
anotherlabelstylebydefiningtheCSSattributelabelstyleinthe
appropriatestyle,whichreferstoanotherstyle.
info Thestylethatisusedfordisplayingadditionalinformationinascreen.
Currentlythisisonlyusedforshowingthecurrentinputmodewhenthe
directinputmodeofaTextFieldoraTextBoxisenabled.Compare

106
TheJ2MEPolishGUI

Style Description
page142formoreinformation.
default ThestylewhichisusedbytheJ2MEPolishGUIwhenthedesired
predefinedstyleisnotdefined.Thedefaultstyleisalwaysdefined,even
whenitisnotexplicitlydefinedinthepolish.cssfile.
tabbar ThisstyledesignsthetabbarofaTabbedForm.
activetab DesignsthecurrentlyactivetabofaTabbedForm.
Inactivetab DesignsalltabsbutthecurrentlyselectedoneofaTabbedForm.

Thenamesofpredefinedstylesmustnotbeusedforstaticstyles,soyoumustnotuseastaticstyle
withthename.titleetc.

DynamicStyles
Dynamicstylescanbeusedtoapplystylestoitemswithoutusing#styledirectivesinthesource
code.Withdynamicstylesthedesignercanworkcompletelyindependentoftheprogrammerand
tryoutnewdesignsforGUIitemswhichhavenotyetanassociatedstaticstyle.Youcanalsocheck
outthepowerandpossibilitiesoftheJ2MEPolishAPIwithoutchangingthesourcecodeofan
existingapplicationatall.
Obviously,dynamicstylesneedabitmorememoryandprocessingtimethanstaticstyles.Itis
recommended,therefore,tousestaticstylesinsteadforfinishedapplications.
Dynamicstylesdonotstartwithadotandusetheselectorsoftheitemstheywanttodesign:
Textsuseeitherp,a,buttonoricon.Screensusethenameofthescreen,e.g.form,list
ortextbox.
p {
font-color: black;
font-size: medium;
background: none;
}
form {
margin: 5;
background-color: gray;
border: none;
font-size: medium;
}

Youcanalsodesignonlyitemswhicharecontainedinotheritemsorscreens:
Thestyleformpdesignsalltextitems(oftheclassStringItem)whicharecontainedinaform:
form p {
font-color: white;
font-size: medium;
}

Staticstylesanddynamicstylescanbeusedtogether,youcandesignallhyperlinks9inthescreen
9 StringItemswhichhavetheappearancemodeItem.HYPERLINK

107
TheJ2MEPolishGUI

withthestyle.startScreenforexamplewiththefollowingstyledeclaration:
.startScreen a {
font-color: blue;
font-size: medium;
font-style: italic;
}

Itemsandscreenshavespecificselectorsfordynamicstyles:
ItemClass Selector Explanation
StringItem p StringItemshowstext.Thepselectorisused,whenthe
itemhastheappearancemodePLAIN.
a Theaselectorisused,whentheitemhastheappearance
modeHYPERLINK.
button Thebuttonselectorisused,whentheitemhasthe
appearancemodeBUTTON.
ImageItem img Showsanimage.
Gauge gauge Showsaprogressindicator.
Spacer spacer Isusedforshowinganemptyspace.TheusageoftheSpacer
itemisdiscouraged,sincethespacescanbesetforallitems
withthemarginandpaddingattributes.
IconItem icon Showsanimagetogetherwithtext.
TextField textfield Allowstextualinputfromtheuser.
DateField datefield Allowstheinputofdatesortimesfromtheuser.
ChoiceGroup choicegroup Containsseveralchoiceitems.
ChoiceItem listitem Showsasinglechoice.Theselectorlistitemisused,when
thisitemiscontainedinanimplicitlist.
radiobox Theselectorradioboxisusedwhenthelistorchoicegroup
hasthetypeexclusive.
checkbox Theselectorcheckboxisusedwhenthelistorchoicegroup
hasthetypemultiple.
popup Theselectorpopupisusedwhenthechoicegrouphasthe
typepopup.

ScreenClass Selector Explanation


List list Showsseveralchoiceitems.
Form form ContainsdifferentGUIitems.
TextBox textbox Containsasingletextfield.

108
TheJ2MEPolishGUI

ExtendingStyles
Astylecanextendanotherstyle.Itinheritsalltheattributesoftheextendedstyle.Withthis
mechanismalotofwritingworkcanbesaved:
.mainScreen {
margin: 10;
font-color: black;
font-size: medium;
font-style: italic;
background-color: gray;
}
.highscoreScreen extends mainScreen {
font-color: white;
background-color: black;
}

IntheaboveexamplethestylehighscoreScreeninheritsallattributesofthemainScreenstyle,
butfontcolorandbackgroundcolorarespecifieddifferently.
Circleinheritanceisnotallowed,sothefollowingexampleresultsinabuilderror:
.baseScreen extends highscoreScreen { /* this extends is invalid! */
margin: 5;
font-color: white;
}
.mainScreen extends baseScreen {
margin: 10;
font-color: black;
font-size: medium;
font-style: italic;
background-color: gray;
}
.highscoreScreen extends mainScreen {
font-color: white;
background-color: black;
}

Theaboveexamplewouldbevalid,whenthestylebaseScreenwouldnotextendthe
highscoreScreenstyle.

CSSSyntax
FollowingrulesdoapplyforCSSstyles:

StructureofaCSSDeclaration

.myStyle { font-color: white; }

selector/nameattribute value
Fig.3:Structureofastyle

Everystylestartswiththeselectorfollowedbyanopeningcurvedparenthesis,anumberof
attributevaluepairsandaclosingcurvedparenthesis.
Theselectorcanconsistofseveralitemnamesandcontainanextendsclause.

109
TheJ2MEPolishGUI

Eachattributevaluepairneedstobefinishedbyasemicolon.

Naming
Stylescanuseanynames,aslongastheyconsistofalphanumericandunderline(_)charactersonly.
Namesarenotcasesensitive.Staticstylesneedtostartwithadot.Staticstylesmustnotusethe
namesofdynamicorpredefinedstyles.AllJavakeywordslikeclass,intorbooleanetcetera
arenotallowedasstylenames.

GroupingofAttributes
Attributescanbegroupedforeasierhandling:
.mainScreen {
font-color: black;
font-size: medium;
font-style: italic;
font-face: system;
}
Theabovecodeisequivalentwiththefollowing:
.mainScreen {
font {
color: black;
size: medium;
style: italic;
face: system;
}
}

Thegroupingmakesthedeclarationsbetterreadableforhumans.

ReferringtoOtherStyles
Whenanotherstyleisreferred,thedotsofstaticstylesdonotneedtobewritten.Stylescanbe
referredinattributesoraftertheextendskeywordintheselectorofastyle.

Comments
Commentscanbeinsertedatanyplaceandstartwith/*andstopwith*/.Everythingbetween
theseboundariesisignored:
/* this style designs the main screen: */
.mainScreen {
/* defining the color of a font: */
font-color: black;
/* sizes are small, medium and large: */
font-size: medium;
/* styles are plain, bold, italic or underlined: */
font-style: italic;
/* the face can either be system, proportional or monospace: */
font-face: system;
}

110
TheJ2MEPolishGUI

CommonDesignAttributes

Structureofpolish.css

Thepolish.cssfilecancontaindifferentsections:
colors:Thecolorssectioncontainsthedefinitionofcolors.
fonts:Thefontssectioncontainsfontdefinitions.
backgrounds:Thebackgroundssectioncontainsbackgrounddefinitions.
borders:Theborderssectioncontainsdefinitionofborders.
rest:Therestofpolish.csscontainstheactualstyledefinitions.
Thedefinedcolors,fonts,backgroundsandborderscanbereferencedintheactualstyledefinitions.
Thismakeschangesveryeasy,sinceyouneedtochangethevalueonlyinoneposition.

StructureofaStyleDefinition
Eachstylecancontaindifferentsections:
margin:Thegapbetweenitems
padding:Thegapbetweentheborderandthecontentofanitem
font:Theusedcontentfontanditscolors
layout:Thelayoutoftheitems.
background:Thedefinitionoftheitem'sbackground
border:Thedefinitionoftheitem'sborder
beforeandafter:Elementswhichshouldbeinsertedbeforeoraftertheitems.
specificattributes:AllattributesforspecificGUIitems.
Anexampleofsuchacompletestyledefinitionisthefollowing:
/* this style designs the currently focused element in a list, form etc: */
focused {
/* margins and paddings: */
margin: 2;
margin-left: 5;
margin-right: 10;
padding: 1;
padding-vertical: 2;
/* font */
font {
color: blue;
size: medium;
face: system;
}
/* layout is centered: */
layout: center;
/* background: */
background-color: gray;
/* no border: /*
border: none;

111
TheJ2MEPolishGUI

/* before: add an image: */


before: url( arrow.png );
/* after: add another image: */
after: url( leftArrow.png );
/* no specific attributes are used in this example*/
}

TheCSSBoxModel:MarginsandPaddings
AllGUIitemssupportthestandardCSSboxmodel:

margintop

border
paddingtop

paddingright
paddingleft

marginright
marginleft

content

paddingbottom

ThemargindescribesthegaptootherGUIitems.Thepaddingdescribesthegapbetweentheborder
oftheitemandtheactualcontentofthatitem.Sofarnodifferentborderwidths(forleft,right,top
andbottom)canbesetwithJ2MEPolish.Sincethisisamorebizarreandseldomusedfeature,not
muchharmisdone.
Themarginandpaddingattributesdefinethedefaultgapsfortheleft,right,topandbottom
elements.Anymarginhasthedefaultvalueof0pixels,whereasanypaddingdefaultsto1pixel.
Nexttotheleft,right,topandbottompadding,J2MEPolishalsoknowstheverticalandthe
horizontalpaddings.Thesedefinethegapsbetweendifferentcontentsections.Thegapbetweenthe
labelofanitemandtheactualcontentisdefinedbythehorizontalpadding.Anotherexampleisthe
icon,whichconsistsofanimageandatext.Dependingonthealignoftheimage,eitherthevertical
orthehorizontalpaddingfillsthespacebetweentheiconimageandtheicontext.
Inthefollowingexample,thetop,rightandbottommarginis5pixels,whereastheleftmarginis
10pixels:
.myStyle {
margin: 5;
margin-left: 10;
font-color: black;
}

Percentagevaluescanalsobeused.Percentagevaluesfortop,bottomandverticalattributesrelate
totheheightofthedisplay.Percentagevaluesforleft,rightandhorizontalattributesrelatetothe
widthofthedisplay:

112
TheJ2MEPolishGUI

.myStyle {
padding-left: 2%;
padding-right: 2%;
padding-vertical: 1%;
font-color: black;
}

Whenthedevicehasawidthof176pixels,apaddingof2%resultsinto3.52pixels,meaning
effectivelyapaddingof3pixels.Atadisplayheightof208pixelsaverticalpaddingof1%results
intoapaddingof2.08pixelsoreffectively2pixels.PleasenotethatthecapabilityScreenSizeof
thedeviceneedstobedefinedwhenyouusepercentagevalues.

TheLayoutAttribute
Thelayoutattributedefineshowtheaffecteditemshouldbealignedandlaidout.Possiblelayout
valuesareforexampleleft,rightorcenter.AlllayoutvaluesoftheMIDP/2.0standardcanbeused:
Layout AlternativeNames Explanation
left Theaffecteditemsshouldbeleftaligned.
right Theaffecteditemsshouldberightaligned.
center horizontalcenter, Theaffecteditemsshouldbecenteredhorizontally.
hcenter
expand horizontalexpand, Theaffecteditemsshouldusethewholeavailable
hexpand width(i.e.shouldfillthecompleterow).
shrink horizontalshrink, Theaffecteditemsshouldusetheminimumwidth
hshrink possible.
top Theaffecteditemsshouldbetopaligned.
bottom Theaffecteditemsshouldbebottomaligned.
vcenter verticalcenter Theaffecteditemsshouldbecenteredvertically.
vexpand verticalexpand Theaffecteditemsshouldusethewholeavailable
height(i.e.shouldfillthecompletecolumn).
vshrink verticalshrink Theaffecteditemsshouldusetheminimumheight
possible.
newlineafter Itemsfollowinganitemwithanewlineafterlayout
shouldbeplacedonthenextline.Currentlythe
newlinesettingswillbeignored,sinceeveryitem
willbeplacedonanewline.
newlinebefore Theaffecteditemsshouldalwaysstartonanewline
(whenthereareanyitemsinfrontofit).Currently
thenewlinesettingswillbeignored,sinceevery
itemwillbeplacedonanewline.
plain default,none Nospecificlayoutshouldbeused,insteadthe
defaultbehaviorshouldbeused.Suchalayoutdoes

113
TheJ2MEPolishGUI

Layout AlternativeNames Explanation


notneedtobedefinedexplicitly,butitcanbeuseful
tooverwriteabasicsetting.

Layoutvaluescanalsobecombined,usingeitherthe||,|,ororandoperators.Alloperators
resultinthesamecombination.Anitemcanbecenteredandusingthewholeavailablewidthwith
followingexample:
.myStyle {
layout: center | expand;
}
Thisisequivalentwith:
.myStyle {
layout: center || expand;
}
Andequivalentwith:
.myStyle {
layout: center and expand;
}
Andequivalentwith:
.myStyle {
layout: center or expand;
}
Andequivalentwith:
.myStyle {
layout: hcenter | hexpand;
}
Andequivalentwith:
.myStyle {
layout: horizontal-center | horizontal-expand;
}

Colors
Colorscanbedefinedinthecolorssectionandineachattributewhichendsoncolor,e.g.font
color,bordercoloretc.

PredefinedColors

The16standardwindowscolorsarepredefined:

Color HexValue Example Color HexValue Example


white #FFFFFF yellow #FFFF00

black #000000 maroon #800000

114
TheJ2MEPolishGUI

Color HexValue Example Color HexValue Example


red #FF0000 purple #800080

lime #00FF00 fuchsia #FF00FF

blue #0000FF olive #808000

green #008000 navy #000080

silver #C0C0C0 teal #008080

gray #808080 aqua #00FFFF

Anotherpredefinedcoloristransparent,whichresultsinantransparentarea.transparentisonly
supportedbysomeGUIelementslikethemenubarofafullscreenmenu.

ThecolorsSection

Thecolorssectionofthepolish.cssfilecancontaincolors,whichcanbereferencedinthestyles,
fonts,borderandbackgroundsections.Youcanevenoverwritethepredefinedcolorstoconfuse
otherdesigners!
colors {
bgColor: #50C7C7;
bgColorLight: #50D9D9;
gray: #7F7F7F;
}

HowtoDefineColors

Acolorcanbedefinedinmanydifferentways:
.myStyle {
font-color: white; /* the name of the color */
border-color: #80FF80; /* a rgb hex value */
start-color: #F00; /* a short rgb-hex-value - this is red */
menu-color: #7F80FF80; /* an alpha-rgb hex value */
background-color: rgb( 255, 50, 128 ); /* a rrr,ggg,bbb value */
fill-color: rgb( 100%, 30%, 50% ); /* a rgb-value with percentage */
label-color: argb( 128, 255, 50, 128 ); /* a aaa, rrr, ggg, bbb value */
}

Colornamesrefertooneofthepredefinedcolorsoracolorwhichhasbeendefinedinthecolors
section:
color: black;orcolor: darkBackgroundColor;

Thehexvaluedefinesacolorwithtwohexadecimaldigitsforeachcolor(RRGGBB).Additionally
thealphablendingcomponentcanbeadded(AARRGGBB).
color: #FF000;definesred.color:#7FFF0000;definesahalftransparentred.

TheshortenedhexvaluedefinesacolorbyaRGBvalueinhexadecimal.Everydigitwillbe
doubledtoretrievethefullhexvalue:
color: #F00;isequivalentwithcolor: #FF0000;
color: #0D2;isequivalentwithcolor: #00DD22;andsoon.

115
TheJ2MEPolishGUI

Argbvaluestartswithrgb(andthenliststhedecimalvalueofeachcolorfrom0upto255:
color: rgb( 255, 0, 0 );definesred.color: rbg( 0, 0, 255);definesblueandsoon.

Alternativelypercentagevaluescanbeusedforrgbcolors:
color: rgb( 100%, 0%, 0% );definesredaswellascolor: rgb( 100.00%, 0.00%, 0.00% )
;.

AlphaRGBcolorscanbedefinedwiththeargb()construct:
color: argb( 128, 255, 0, 0 );definesahalftransparentred.Fortheargbconstruct
percentagevaluescanbeusedaswell.

AlphaBlending

Colorswithalphablendingcanbedefinedwithhexadecimalorargbdefinitions(seeabove).An
alphavalueof0resultsinfullytransparentpixels,whereasthevalueFF(or255or100%)resultsin
fullyopaquepixels.Somedevicessupportvaluesbetween0andFF,whichresultsintransparent
colors.ColorswithaspecifiedalphachannelcanonlybeusedbyspecificGUIitems.Pleasereferto
thedocumentationofthespecificdesignattributes.

Fonts
ManyGUIItemshavetextelements,whichcanbedesignedwiththefontattributes:

Attribute PossibleValues Explanation


color Referencetoacolorordirectdeclaration Dependingonthenumberofcolorsthe
ofthecolor. devicesupports,colorscanlook
differentlyontheactualdevice.
bitmap Thenameofthebitmapfont.The Withthebitmapattributeabitmap
extension.bmfisnotneeded. fontcanbeusedinsteadofthesystem,
proportionalandmonospacefonts.
Pleasenotethatbitmapfontscannotbe
changedinneithersize,colororstyle.
Comparethefollowingsectionfora
detaileddiscussionofbitmapfonts.
face system(default,normal) Thedefaultfontfacewhichisused
whenthefontfaceorlabelface
attributeisnotset.
proportional Aproportionalface.Thisisonsome
devicesactuallythesamefontfaceas
thesystemfont.
monospace Afontfaceinwhicheachcharacterhas
thesamewidth.
size small Thesmallestpossiblefont.
medium(default,normal) Thedefaultsizefortexts.
large(big) Thelargestpossiblefontsize.

116
TheJ2MEPolishGUI

Attribute PossibleValues Explanation


style plain(default,normal) Thedefaultstyle.
bold Aboldthickstyle.
italic(cursive) Acursivestyle.
underlined Notreallyastyle,justanunderlined
text.

Anexamplefontspecification:
.myStyle {
font-color: white;
font-face: default; /* same as system or normal */
font-size: default; /* same as medium or normal */
font-style: bold;
}

Thesamespecificationcanalsobewrittenasfollows:
.myStyle {
font {
color: white;
style: bold;
}
}
Inthefontdefinitiontheabovefaceandsizeattributescanbeskipped,sincetheyonlydefinethe
defaultbehavioranyhow.

BitmapFonts
BitmapFontscanbeusedinsteadoftheusualpredefinedfontsforanytextelementsliketitles,
StringItems,etc.

CreatingBitmapFonts

BitmapFontscanbecreatedoutofanyTrueTypeFonts(*.ttf)usingthe
${polish.home}/bin/fonteditorexecutable.Insomecasesitmightbebeneficialtooptimizethe
createdPNGimagemanuallyfordecreasingthesizeoftheimageandmakingmanualadjustments.
Thecreatedbitmapfontsfiles(*.bmf)canalsobefinetunedusingthebinarydataeditor
${polish.home}/bin/binarydataeditor.JustselecttheFile>openinbinary
editorcommand.
Thecreatedbitmapfontneedstobecopiedintotheresourcesfolderoftheproject.

UsingBitmapFontsintheJ2MEPolishGUI

ThecreatedbitmapfontscanbeusedforanytextbaseditemsintheJ2MEPolishGUI.Theycanbe
integratedusingthefontbitmapattribute.The.bmfextensiondoesnotneedtobegiven.Inthe
followingexamplethechina.bmffontisusedforthecurrentlyfocuseditem:
focused {
font-bitmap: china;
background-color: yellow;

117
TheJ2MEPolishGUI

layout: center | expand;


}

UsingBitmapFontsDirectly

Thebitmapfontscanalsobeuseddirectlyintheprogramcodewiththehelpofthe
de.enough.polish.util.BitMapFontclass.PleasecomparetheJavaDocdocumentationformore
information.
Thisexampleusesabitmapfontfordisplayingatext:
import de.enough.polish.util.*;

public class MyScreen extends Canvas {


private BitMapFont bitMapFont = BitMapFont.getInstance( /china.bmf );
private BitMapFontViewer textViewer;
public MyScreen() throws IOException {
this.textViewer = this.bitMapFont.getViewer( Hello World! );
...
}
...
public void paint( Graphics g ) {
int x = 20;
int y = 50;
this.viewer.paint( x, y, g );
}
}

Labels
AllGUIItemscanhavealabel,whichisdesignedusingthepredefinedstylelabel.Onecan
specifyanotherstylebyusingthelabelstyleattribute:
.myStyle {
font {
color: white;
style: bold;
}
label-style: myLabelStyle;
}

.myLabelStyle {
font-style: bold;
font-color: green;
background-color: yellow;
}

Itisoftenadvisabletouseseparateitemsforlabelsandcontents.Inthatwayyoucangetaclean
designbyusingatable,inwhichalllabelsareplacedontheleftsideandallinputfieldsetconthe
rightside.Tablesaredefinedbyusingthecolumnsattributeofthecorrespondingscreen,
comparetheScreensdescriptiononpage131.
Whenyouwanttohavealinebreakaftereachlabel,justaddthenewlineaftervaluetothe
layout:
label {
font-style: bold;
font-color: green;
background: none;

118
TheJ2MEPolishGUI

layout: left | newline-after;


}

BackgroundsandBorders
Eachstylecandefineaspecificbackgroundandborder.Therearemanydifferenttypesof
backgroundsandbordersavailable,ofwhichsomeareevenanimated.
Aspecificationofasimplebackgroundandborderisthefollowingexample:
.myStyle {
background-color: white;
border-color: gray;
border-width: 2;
}
Thisexamplecreatesawhiterectangularbackgroundwithagrayborder,whichis2pixelwide.
.myStyle {
background {
type: pulsating;
start-color: white;
end-color: pink;
steps: 30;
}
}
Theaboveexamplecreatesabackgroundwhichcolorisconstantlychangingbetweenwhiteand
pink.30colorshadesareusedfortheanimation.
Whennobackgroundorbordershouldbeused,thenonevaluecanbeset:
.myStyle {
background: none;
border: none;
}

Ifmorecomplextypesshouldbeused,thebackgroundorbordertypeneedstobespecified
explicitly.Thefollowingexampleillustratesthisforanbackground,whichcolorschangeallthe
time:
TheavailablebackgroundandbordertypesareexplainedindetailinthesectionSpecificDesign
Attributes.

BeforeandAfterAttributes
ThebeforeandafterattributescanbeusedtoinsertcontentbeforeorafterGUIitemswhichhave
thespecifiedstyle.
ThefollowingexampleaddsaheartpictureaftertheactualGUIitems.Thefocusedstyleisa
predefinedstylewhichisusedforlists,forms,andsoon.
focused {

119
TheJ2MEPolishGUI

after: url( heart.png );


background: none;
border-type: round-rect;
border-arc: 6;
border-color: yellow;
border-width: 2;
layout: left | expand;
font-color: black;
}

Currentlyonlyimagescanbeincluded.

SpecificDesignAttributes

ManyGUIitemssupportspecificCSSattributes.
Fig.4:Theafterattributein
Backgrounds action.
TherearemanydifferentbackgroundtypeswhichmakeuseofspecificCSSattributes.When
anotherbackgroundthanthedefaultsimplebackgroundortheimagebackgroundshouldbeused,
thebackgroundtypeattributeneedstobedeclared.
Whennobackgroundatallshouldbeused,thebackground: none;declarationcanbeused.

SimpleBackground

Thesimplebackgroundjustfillsthebackgroundwithonecolor.Whennobackgroundtypeis
specified,thesimplebackgroundisusedbydefault,unlessthebackgroundimageattributeisset.
Inthelatercasetheimagebackgroundwillbeused.
Thesimplebackgroundsupportsthecolorattribute:

Attribute Required Explanation


color Yes Thecolorofthebackground,eitherthenameofthecolororadirect
definition.

Thefollowingstylesuseayellowbackground:
.myStyle {
background-color: yellow;
}
.myOtherStyle {
background-color: rgb( 255, 255, 0 );
}

RoundRectBackground

Theroundrectbackgroundpaintsarectangularbackgroundwithroundedges.Itsupportsfollowing
attributes:

Attribute Required Explanation


type Yes Thetypeneedstoberoundrectorroundrect.

120
TheJ2MEPolishGUI

Attribute Required Explanation


color No Thecolorofthebackground,eitherthenameofthecolororadirect
definition.Thedefaultcoloriswhite.
arc No Thediameterofthearcatthefourcorners.Defaultsto10pixels,when
noneisspecified.
arcwidth No Thehorizontaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.
archeight No Theverticaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.

Thisexamplecreatesapurplebackgroundwithanarcdiameterof6pixels:
.myStyle {
background {
type: round-rect;
color: purple;
arc: 6;
}
}

Thefollowingexampleusesadifferenthorizontalarcdiameter:
.myStyle {
background-type: round-rect;
background-color: purple;
background-arc: 6;
background-arc-width: 10;
}

ImageBackground

Theimagebackgroundusesanimageforpaintingthebackground.Thisbackgroundtypeisusedby
defaultwhennotypeissetandthebackgroundimageattributeisset.Thebackgroundsupports
followingattributes:

Attribute Required Explanation


type No Whenusedneedstobeimage.
color No Thecolorofthebackground,eitherthenameofthecolor,adirect
definitionortransparent.Thedefaultcoloriswhite.Thiscolorcan
onlybeseenwhentheimageisnotbigenough.
image Yes TheURLoftheimage,e.g.url(background.png)
anchor No Theanchoroftheimagewhennotspecifiedtheimagewillbecentered
("horizontalcenter|verticalcenter").Youcanuseacombinationof
"top","verticalcenter"(="vcenter"),"bottom"and"left","horizontal
center"(="hcenter"="center"),"right".E.g."top|left".
repeat No Eitherrepeat,norepeat,repeatx/repeathorizontalorrepeat

121
TheJ2MEPolishGUI

Attribute Required Explanation


y/repeatvertical.Determineswhetherthebackgroundshouldbe
repeated,repeatedhorizontallyorrepeatedvertically.Defaultisno
repeat.
padding No Thehorizontalgapbetweentiles,canbenegativeforoverlappingthe
horizontal tiles.Defaultsto0.Isonlyapplicablewhentherepeatmodeisactivated.
padding No Theverticalgapbetweentiles,canbenegativeforoverlappingthetiles.
vertical Defaultsto0.Isonlyapplicablewhentherepeatmodeisactivated.
overlap No Defineswhetherthetilesshouldoverlapovertheactualbackgroundarea
whentheydon'tfitexactlyintotheactualbackgroundarea.Either
true/yesorno/false.Defaultstofalse.Isonlyapplicablewhen
therepeatmodeisactivated.

Thefollowingstyleusestheimagegradient.pngasabackground:
.myStyle {
background-image: url( gradient.png );
background-anchor: top | center;
background-color: rgb( 69, 81, 77 );
}

Thisstyleusestheimageheart.pngasarepeatedbackground:
.myStyle {
background-image: url( heart.png );
background-repeat: repeat;
}

CircleBackground

Thecirclebackgroundpaintsacircularorellipticalbackground.Itsupportsfollowingattributes:
Attribute Required Explanation
type Yes Thetypeneedstobecircle.
color No Thecolorofthebackground,eitherthenameofthecolororadirect
definition.Defaultstowhite.
diameter No Withthediameterattributeitcanbeensuredthatalwaysacircleand
neveranellipseispainted.Thediameterthendefinesthediameterofthe
circle.

Thefollowingexampleusesagreencirclebackgroundwithadiameterof20pixels:
.myStyle {
background-type: circle;
background-color: green;
background-diameter: 20;
}

122
TheJ2MEPolishGUI

PulsatingBackground

Thepulsatingbackgroundanimatesthecolorofthebackground.Thecolorischangingfromastart
colortoanendcolor.Itsupportsfollowingattributes:

Attribute Required Explanation


type Yes Thetypeneedstobepulsating.
startcolor Yes Thecolorofthebackgroundatthebeginningoftheanimationsequence.
endcolor Yes Thecolorofthebackgroundattheendoftheanimationsequence.
steps Yes Defineshowmanycolorshadesbetweenthestartandtheendcolor
shouldbeused.
repeat No Eitheryes/trueorno/false.Determineswhethertheanimation
shouldberepeated.Defaultstoyes.
backand No Eitheryes/trueorno/false.Determineswhethertheanimation
forth sequenceshouldberunningbackwardstothestartcoloragain,afterit
reachestheendcolor.Whennoisselected,theanimationwilljump
fromtheendcolordirectlytothestartcolor(whenrepeatisenabled).
Defaultstoyes.

Thefollowingstylestartswithawhitebackgroundandstopswithayellowbackground:
.myStyle {
background {
type: pulsating;
start-color: white;
end-color: yellow;
steps: 15;
repeat: false;
back-and-forth: false;
}
}

PulsatingCircleBackground

Thepulsatingcirclebackgroundpaintsacircularorbackgroundwhichsizeconstantlyincreasesand
decreases.Itsupportsfollowingattributes:
Attribute Required Explanation
type Yes Thetypeneedstobepulsatingcircle.
color No Thecolorofthebackground,eitherthenameofthecolororadirect
definition.Defaultstowhite.
min Yes Theminimumdiameterofthecircle.
diameter
max Yes Themaximumdiameterofthecircle.
diameter

123
TheJ2MEPolishGUI

Thefollowingexampleusesagreenpulsatingcirclebackgroundwithaminimumdiameterof20
pixelsandamaximumdiameterof40pixels:
.myStyle {
background-type: pulsating-circle;
background-color: green;
background-min-diameter: 20;
background-max-diameter: 40;
}

PulsatingCirclesBackground

Thepulsatingcirclesbackgroundpaintsananimatedbackgroundofevergrowingcircles.It
supportsfollowingattributes:

Attribute Required Explanation


type Yes Thetypeneedstobepulsatingcircles.
firstcolor Yes Thefirstcirclecolor,eitherthenameofthecolororadirectdefinition.
second Yes Thesecondcirclecolor,eitherthenameofthecolororadirect
color definition.
min Yes Theminimumdiameterofthecircle.
diameter
max Yes Themaximumdiameterofthecircle.
diameter
circles Yes Thenumberofcircleswhichshouldbepainted.
number
step No Thenumberofpixelseachcircleshouldgrowineachanimationphase.
Floatvalueslike1.5arealsoallowed.Thisdefaultsto1pixel.

Thefollowingexampleusesthepulsatingcirclesbackgroundwithadarkandwithabrightcolor:
.myStyle {
background {
type: pulsating-circles;
first-color: bgColor;
second-color: brightBgColor;
min-diameter: 0;
max-diameter: 300;
circles-number: 8;
step: 2.5;
}
}

OpeningBackground

Theopeningbackgroundpaintsananimatedbackgroundwhichheightstartssmallandthen
increaseswheneveritchangestheposition.Itsprimaryuseisforthefocusedstyle.Itsupports
followingattributes:

124
TheJ2MEPolishGUI

Attribute Required Explanation


type Yes Thetypeneedstobeopening.
color Yes Thebackgroundcolor,eitherthenameofthecolororadirectdefinition.
startheight No Theheightofthebackgroundimmediatelyafterithaschangedits
position.Thisdefaultsto1pixel.
steps No Thenumberofpixelsbywhichtheheightshouldbeincreasedineach
animationstep.Thisdefaultsto4pixels.Whentheheightisasbigasthe
normalbackgroundheight,theanimationisstopped.

Thefollowingexampleusestheopeningbackground:
.myStyle {
background {
type: opening;
color: bgColor;
start-height: 2;
steps: 4;
}
}

OpeningRoundRectBackground

Theopeningroundrectanglebackgroundpaintsananimatedbackgroundwhichheightstartssmall
andthenincreaseswheneveritchangestheposition.Itsprimaryuseisforthefocusedstyle.It
supportsfollowingattributes:

Attribute Required Explanation


type Yes Thetypeneedstobeopeningroundrect.
color Yes Thebackgroundcolor,eitherthenameofthecolororadirectdefinition.
startheight No Theheightofthebackgroundimmediatelyafterithaschangedits
position.Thisdefaultsto1pixel.
steps No Thenumberofpixelsbywhichtheheightshouldbeincreasedineach
animationstep.Thisdefaultsto4pixels.Whentheheightisasbigasthe
normalbackgroundheight,theanimationisstopped.
border No Thewidthoftheborder,defaultsto0(noborder).
width
bordercolor No Thecoloroftheborder,defaultstoblack.
arc No Thediameterofthearcatthefourcorners.Defaultsto10pixels,when
noneisspecified.
arcwidth No Thehorizontaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.
archeight No Theverticaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.

125
TheJ2MEPolishGUI

Thefollowingexampleusestheopeningroundrectbackground:
.myStyle {
background {
type: opening-round-rect;
color: bgColor;
start-height: 2;
steps: 4;
border-width: 2;
border-color: darkBgColor;
}
}

RoundTabBackground

Theroundtabbackgroundpaintsarectangularbackgroundwherethetopedgesarerounded.It
supportsfollowingattributes:
Attribute Required Explanation
type Yes Thetypeneedstoberoundtab
color No Thecolorofthebackground,eitherthenameofthecolororadirect
definition.Thedefaultcoloriswhite.
arc No Thediameterofthearcatthefourcorners.Defaultsto10pixels,when
noneisspecified.
arcwidth No Thehorizontaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.
archeight No Theverticaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.

Thisexamplecreatesapurplebackgroundwithanarcdiameterof6pixels:
.myStyle {
background {
type: round-tab;
color: purple;
arc: 6;
}
}

Thefollowingexampleusesadifferenthorizontalarcdiameter:
.myStyle {
background-type: round-tab;
background-color: purple;
background-arc: 6;
background-arc-width: 10;
}

SmoothColorBackground
Thesmoothcolorbackgroundpaintsangradientbackground.Itsupportsfollowingattributes:

Attribute Required Explanation

126
TheJ2MEPolishGUI

Thecolorofthebackground,eitherthenameofthecolororadirect
color Yes
definition.
gradient Thecolorforthegradient,eitherthenameofthecolororadirect
Yes
color definition.
stroke No Thedefaultvalueis0.Foreffectssetstroke1.
Thisexamplecreatesaredbackgroundwithangradienttoyellow:
.myStyle {
background {
type: smooth-color;
color: red;
gradient-color: yellow;

}
}

TigerStripesBackground
ThetigerstripesbackgroundpaintsanbackgroundwithrandomizednumbersofStripes.Itsupports
followingattributes:

Attribute Required Explanation


Thecolorofthebackground,eitherthenameofthecolororadirect
color Yes
definition.
stripes Thecolorforthestripes,eitherthenameofthecolororadirect
Yes
color definition.
number Yes Theposiblenumberofstripesthatcanbedisplayed.
Thisexamplecreatesaredbackgroundwithanmaximumof25blackstripes:
.myStyle {
background {
type: tiger-stripes;
color: red;
stripe-color: black;
number: 25;
}
}

BallGamesBackground
Theballgamesbackgroundpaintsananimatedbackgroundwithannumberofspriteswhich
movingthroughthebackground.Itsupportsfollowingattributes:

127
TheJ2MEPolishGUI

Attribute Required Explanation


Thecolorofthebackground,eitherthenameofthecolororadirect
color Yes
definition.
number Yes Thenumberofspritesthatweredisplayed.
bordercolor Yes Thebordercolorfromthebackground.
image Yes Theimageforthesprite.
image
Yes Thewidthforthesprite.
width
image
Yes Theheightforthesprite.
height
Thisexamplecreatesbluebackgroundwith5sprites.Thespritesincludethegiven
image(player.png):
.myStyle {
background {
type: ball-games;
image: url( player.png );
image-width: 15;
image-height: 15;
color: blue;
number: 5;
border-color: green;

}
}

Borders
TherearemanydifferentbordertypeswhichmakeuseofspecificCSSattributes.Whenanother
borderthanthedefaultsimplebordershouldbeused,thebordertypeattributeneedstobedeclared.
Whennoborderatallshouldbeused,theborder: none;declarationcanbeused.

SimpleBorder

Thesimpleborderpaintsarectangleborderinonecolor.Thetypeattributedoesnotneedtobeset
forthesimpleborder,sincethisisthedefaultborder.Theonlysupportedattributesarethecolorand
thewidthoftheborder:
Attribute Required Explanation
color Yes Thecoloroftheborder,eitherthenameofthecolororadirect
definition.
width No Thewidthoftheborderinpixels.Defaultsto1.

128
TheJ2MEPolishGUI

Thefollowingstyleusesablackborderwhichis2pixelswide:
.myStyle {
border-color: black;
border-width: 2;
}

RoundRectBorder

Theroundrectborderpaintsarectangularborderwithroundedges.Itsupportsfollowingattributes:
Attribute Required Explanation
type Yes Thetypeneedstoberoundrectorroundrect.
color Yes Thecoloroftheborder,eitherthenameofthecolororadirect
definition.
width No Thewidthoftheborderinpixels.Defaultsto1.
arc No Thediameterofthearcatthefourcorners.Defaultsto10pixels,when
noneisspecified.
arcwidth No Thehorizontaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.
archeight No Theverticaldiameterofthearcatthefourcorners.Defaultstothearc
value,whennoneisspecified.

Thisexamplecreatesa2pixelswidepurpleborderwithanarcdiameterof6pixels:
.myStyle {
border {
type: round-rect;
color: purple;
width: 2;
arc: 6;
}
}

Thefollowingexampleusesadifferenthorizontalarcdiameter:
.myStyle {
border-type: round-rect;
border-color: purple;
border-width: 2;
border-arc: 6;
border-arc-width: 10;
}

ShadowBorder

Theshadowborderpaintsashadowyborder.Followingattributesaresupported:

129
TheJ2MEPolishGUI

Attribute Required Explanation


type Yes Thetypeneedstobeshadow,bottomrightshadoworright
bottomshadow.
color Yes Thecoloroftheborder,eitherthenameofthecolororadirect
definition.
width No Thewidthoftheborderinpixels.Defaultsto1.
offset No Theoffsetbetweenthecornerandthestartoftheshadow.Defaultsto
1pixel,whennoneisspecified.

Currentlyonlyabottomrightshadowissupported,sotheborderispaintedbelowtheitemand
rightoftheitem.
Thefollowingexampleusesagreenshadowborder:
.myStyle {
border-type: shadow;
border-color: green;
border-width: 2;
border-offset: 2;
}

Top,Bottom,LeftandRightBorder

Theseborderpaintsasimpleborderononesidethecorrespondingitem.Followingattributesare
supported:
Attribute Required Explanation
type Yes Thetypeneedstobetop,bottom,leftorright.
color Yes Thecoloroftheborder,eitherthenameofthecolororadirect
definition.
width No Thewidthoftheborderinpixels.Defaultsto1.

Thefollowingexampleusesagreenborderonthebottomofthetitle:
title {
border-type: bottom;
border-color: green;
border-width: 2;
}

CircleBorder

Thecircleborderpaintsaroundorellipticalborderandsupportsfollowingattributes:

Attribute Required Explanation


type Yes Thetypeneedstobecircle.

130
TheJ2MEPolishGUI

Attribute Required Explanation


color No Thecoloroftheborder,eitherthenameofthecolororadirect
definition.Defaultstoblack.
width No Thewidthoftheborderinpixels.Defaultsto1.
strokestyle No Eithersolidordotted.Definesthepaintingstyleoftheborder.
Defaultstosolid.

Thefollowingexampleusesagreencircleborderwithatwopixelwidedottedline:
.myStyle {
border-type: circle;
border-color: green;
border-width: 2;
border-stroke-style: dotted;
}

Screens:List,FormandTextBox

PredefinedStylesforLists,FormsandTextBoxes

AllscreenshaveatitleandoneorseveralembeddedGUIitems.InaFormorListoneitemis
usuallyfocused.Screenscanalsohaveadesignablemenu,whentheapplicationusesafullscreen
mode10.Someoftheusedstylescanalsouseadditionalattributes.
StyleName Add.Attributes Explanation
title Thetitleofascreen.
focused Thestyleofthecurrentlyfocusediteminthescreen.
menu Thestyleofthefullscreenmenu.
focusedstyle Thenameofthestyleforthecurrentlyfocusedmenuitem.
menubarcolor Thebackgroundcolorofthemenubar.Eitherthenameor
thedefinitionofacolorortransparent.Defaultsto
white.
labelcolor,label Thefontofthemenucommands(likeSelector
face,labelsize, Cancel).Defaultcolorisblack,defaultfontisthe
labelstyle systemfontinaboldstyleandmediumsize.
menuItem Thestyleforthecommandsinthemenu.Whennot
defined,themenustylewillbeused.

Pleaserefertopage145formoreinformationaboutdesigningthemenubar.

AdditionalAttributesforScreens

Eachscreenitselfcanhavesomeadditionalattributes:

10 Thefullscreenmodecanbeactivatedbysettingthe<build>attributefullscreentoeithermenuoryesinthe
build.xmlfile.

131
TheJ2MEPolishGUI

Attribute Required Explanation


focusedstyle No Thenameofthestyleforthecurrentlyfocuseditem.Defaults
tothepredefinedfocusedstyle.
titlestyle No Thenameofthecustomstyleforthetitleofthescreen.This
defaultstothepredefinedtitlestyle.
viewtype No Theviewtypecanbeusedfordefiningverydifferentandeven
animatedviewsoftheitemsinascreen.Anexampleisthe
droppingviewtypeinwhichthecontaineditemsseemtofall
fromthetoptotheirpositions.Pleasenotethatnotallview
typessupportthecolumnsandcolumnswidthattributes.
columns No Thenumberofcolumns.Thiscanbeusedtolayouttheitemsin
atable.Defaultsto1column.
columnswidth No Eithernormal,equalorthewidthforeachcolumnina
commaseparatedlist(e.g.columns-width: 60,60,100;).
Defaultstonormal,meaningthateachcolumnusesasmuch
spaceasthewidestitemofthatcolumnneeds.
Theequalwidthleadstocolumnswhichhaveallthesame
width.
Theexplicitlistofcolumnwidthsresultsintheusageofthose
widths.
menubarcolor No Thecolorofthemenubar.Thisoverridesthesettingsinthe
predefinedstylemenu.Thisattributeisonlyused,whenthe
menufullscreensettingisactivatedinthebuild.xmlfile.
scrollindicatorcolor No Thecoloroftheelementwhichisshownwhenthescreencan
bescrolled.Thedefaultcolorisblack.
showtextintitle No AnattributeforListsonly,whichcanbeeithertrueor
false.Whentrueisgiven,onlytheimageelementsofthe
Listwillbeshownandthetextelementswillbeusedastitles.
Thetitlewillbeupdatedwitheachnewselection.
foregroundimage No TheURLofaimagethatshouldbepaintedattheveryfrontof
thescreen,e.g."url(mascot.png)".
foregroundx No Thexpositionoftheforegroundimageinpixelsfromthethe
leftborder.
foregroundy No Theypositionoftheforegroundimageinpixelsfromthethe
topborder.

132
TheJ2MEPolishGUI

Thefollowingexampleusessomeoftheseadditionalattributes:
list {
background-image: url( bg.png );
columns: 2;
columns-width: equal;
focused-style: .listFocusStyle; /* this style needs
to be defined, too */
}

TextBoxesalsosupportadirectinputmodeandallCSSattributesofthe
textfield,pleasecomparethediscussiononpage142formore
information.
Fig.5:Usingcolumnsinstead
DynamicStylesforScreens ofanormallist.

Dynamicstylescanbeusedwhennostylesareexplicitlysetintheapplicationcode(comparepage
107).

List
Alistusesthedynamicselectorlistandalwayscontainschoiceitems.Theselectoroftheseitems
dependsonthetypeofthelist.Animplicitlistcontainsalistitem,amultiplelistcontainsa
checkboxandanexclusivelistcontainsaradiobox.
list {
background-color: pink;
}
definesthebackgroundcolorforscreensofthetypeList.

listitem { /* you could also use list listitem */


font-style: bold;
}
definesthefontstylefortheitemsinanimplicitlist.

Form
AformusesthedynamicselectorformandcancontaindifferentGUIitems.
form {
background-color: pink;
}
definesthebackgroundcolorforscreensofthetypeForm.

form p {
font-style: bold;
}
definesthefontstylefornormaltextitemsinaForm.

TextBox
ATextBoxusesthedynamicselectortextboxandcontainsasingletextfielditem.

Commands

AmultipleListorChoiceGroupaddsthecommandsMarkandUnmarkbydefaulttothemenu.

133
TheJ2MEPolishGUI

Thenamesofthecommandscanbechangedeasily,comparepage76.Ifyouwanttosuppressthe
commandscompletely,thepolish.ChoiceGroup.suppressMarkCommandsvariablehastobeset:
<variable name="polish.ChoiceGroup.suppressMarkCommands" value="true"/>

ThesameholdstruefortheSelectcommandinimplicitandpopupListsandChoiceGroups:
<variable name="polish.ChoiceGroup.suppressSelectCommand" value="true"/>

ATextBoxorTextFieldaddstheClearandDeletecommandstothemenubydefault.The
namesofthesecommandscanbechangedeasily,comparepage76.Ifyouwanttosuppressthe
commandscompletely,thepolish.TextField.suppressCommandsvariablehastobeset:
<variable name="polish.TextField.suppressCommands" value="true"/>

Example

Thefollowingexampledesignsthemainmenuofanapplication,whichisimplementedusingaList.
colors {
pink: rgb(248,39,186);
darkpink: rgb(185,26,138);
}

menu {
margin-left: 2;
padding: 2;
background {
type: round-rect;
color: white;
border-width: 2;
border-color: yellow;
}
focused-style: .menuFocused;
menubar-color: transparent;
menufont-color: white;
}

menuItem {
margin-top: 2;
padding: 2;
padding-left: 5;
font {
color: black;
size: medium;
style: bold;
}
layout: left;
}

.menuFocused extends .menuItem {


background-color: black;
font-color: white;
layout: left | horizontal-expand;
after: url(heart.png);
}

title {

134
TheJ2MEPolishGUI

padding: 2;
margin-top: 0;
margin-bottom: 5;
margin-left: 0;
margin-right: 0;
font-face: proportional;
font-size: large;
font-style: bold;
font-color: white;
background {
color: darkpink;
}
border: none;
layout: horizontal-center | horizontal-expand;
}

focused {
padding: 2;
padding-vertical: 3;
padding-left: 3;
padding-right: 3;
padding-top: 10;
padding-bottom: 10;
background-type: round-rect;
background-arc: 8;
background-color: pink;
border {
type: round-rect;
arc: 8;
color: yellow;
width: 2;
}
font {
style: bold;
color: black;
size: small;
}
layout: expand | center;
}

list {
padding-left: 5;
padding-right: 5;
padding-vertical: 10;
padding-horizontal: 10;
background {
color: pink;
image: url( heart.png );
}
columns: 2;
columns-width: equal;
layout: horizontal-expand | horizontal-center | vertical-center;
}

listitem {
margin: 2; /* for the border of the focused style */
padding: 2;
padding-vertical: 3;
padding-left: 3;

135
TheJ2MEPolishGUI

padding-right: 3;
padding-top: 10;
padding-bottom: 10;
background: none;
font-color: white;
font-style: bold;
font-size: small;
layout: center;
icon-image: url( %INDEX%icon.png );
icon-image-align: top;
}

ViewTypes

ViewtypescanbeusedforanimatingForms,Lists,ChoiceGroupsorevenmenus.Thereareseveral
viewtypesavailable,whichareusuallydefinedinascreenstyle,e.g.:
.mainScreen {
padding-left: 5;
padding-right: 5;
view-type: dropping;
}

Youcanuseeithera(predefined)nameoftheviewtypeorthefullyqualifiedclassnameofthat
type,whichneedstoextendthede.enough.polish.ui.ContainerViewclass.

DroppingView

Thedroppingviewshowsananimationofdroppingandbouncingitems.Itisactivatedby
specifyingthedroppingviewtypeandsupportsfollowingadditionalattributes:

Attribute Required Explanation


droppingviewspeed No Thespeedinpixelsperanimationstep.Thedefaultspeedis10.
droppingviewrepeat No Defineswhethertheanimationshouldberepeatedeachtime
animation thescreenisshown.Possiblevaluesaretrueandfalse.
Thisdefaultstofalse.
droppingview No Themaximumbouncingheightinpixels.Thisdefaultsto30.
maximum
droppingview No Thevaluebywhichthemaximumisdecreasedforeach
damping followingitem.Byhavingadamping,thetopitemsseemto
bouncehigherthanlowerones.Thedefaultdampingis10.
droppingview No Themaximumallowednumberofbounces.Thisdefaultsto5.
maxperiode

.mainScreen {
padding-left: 5;
padding-right: 5;
view-type: dropping;
droppingview-speed: 15;
droppingview-damping: 5;
droppingview-maxperiode: 2;
}

136
TheJ2MEPolishGUI

ShuffleView

Theshuffleviewanimatestheitemsbymovingthemfromtheleftandrightsideintotheirfinal
targetposition.Itisactivatedbyspecifyingtheshuffleviewtypeandsupportsfollowing
additionalattributes:
Attribute Required Explanation
shuffleviewspeed No Thespeedinpixelsperanimationstep.Thedefaultspeedis10.
shuffleviewrepeat No Defineswhethertheanimationshouldberepeatedeachtime
animation thescreenisshown.Possiblevaluesaretrueandfalse.
Thisdefaultstofalse.

.mainScreen {
padding-left: 5;
padding-right: 5;
view-type: shuffle;
shuffleview-speed: 15;
}

MIDP/2.0View

TheMIDP/2.0viewarrangestheitemsjustliketheMIDP/2.0standardencouragesit:theitemsare
alllinedupintoonerowuntilthereisnotenoughspaceanymoreoruntilanitemwitha"newline
after"or"newlinebefore"layoutisinserted.Itisactivatedbyspecifyingthemidp2viewtype
andsupportsnoadditionalattributes.
.mainScreen {
padding-left: 5;
padding-right: 5;
view-type: midp2;
}

TheStringItem:Text,HyperlinkorButton
Textshavenospecificattributes,butthepaddingverticalattributehasaspecialmeaning:

Attribute Required Explanation


paddingvertical No Thespacebetweenthelineswhentherethetextcontainsline
breaks.

Dependingontheappearancemode11ofthetext,eitherthep,theaorthebuttonselectoris
usedfordynamicstyles:

DynamicSelector Explanation
p Thepselectorisusedfornormaltexts.
a Theaselectorisusedforhyperlinks.

11 TheappearancemodecanbesetintheapplicationcodewithItem.setAppearanceMode(int).

137
TheJ2MEPolishGUI

DynamicSelector Explanation
button Thebuttonselectorisusedforbuttons.

Seethegeneralexplanationofdynamicstylesonpage107formoredetails.

TheIconItem
Iconscanonlybeuseddirectly.Iconssupportfollowingadditionalattributes:

Attribute Required Explanation


iconimage No TheURLoftheimage,e.g.icon-image: url(icon.png);.
Thekeyword%INDEX%canbeusedforaddingtheposition
oftheicontothename,e.g.
icon-image: url(icon%INDEX%.png);.Theimageused
forthefirsticonwillbeicon0.png,thesecondiconwilluse
theimageicon1.pngandsoon.Defaultstonone.
iconimagealign No Thepositionoftheimagerelativetothetext.Eithertop,
bottom,leftorright.Defaultstoleft,meaningthatthe
imagewillbedrawnleftofthetext.

Thisexampleusestheattributesfordesigningallicons:
icon {
background: none;
font-color: white;
font-style: bold;
icon-image: url( %INDEX%icon.png );
icon-image-align: top;
}

Whentheiconitemhasarightimagealignandthelayoutissettohorizontalexpand,theimage
willbedrawndirectlyattherightborderoftheitem(withagapspecifiedbythepaddingright
attribute).Otherwisetheimagewillbedrawnrightofthetextwiththespecifiedhorizontalpadding.

TheChoiceItem
TheChoiceItemisusedinlistsandinchoicegroups.Itsupportsfollowingadditionalattributes:
Attribute Required Explanation
iconimage No TheURLoftheimage,e.g.icon-image: url(icon.png);.
Thekeyword%INDEX%canbeusedforaddingtheposition
oftheitemtothename,e.g.
icon-image: url(icon%INDEX%.png);.Theimageused
forthefirstitemwillbeicon0.png,theseconditemwilluse
theimageicon1.pngandsoon.
iconimagealign No Thepositionoftheimagerelativetothetext.Eithertop,
bottom,leftorright.Defaultstoleft,meaningthatthe

138
TheJ2MEPolishGUI

Attribute Required Explanation


imagewillbedrawnleftofthetext.
choicecolor No Thecolorinwhichthecheckorradioboxwillbepainted.
Defaultstoblack.
checkboxselected No TheURLoftheimageforaselecteditem.Thiswillbeused
radioboxselected onlywhenthetypeofthelistorofthechoicegroupiseither
exclusiveormultiple.Defaultisasimpleimagedrawninthe
definedchoicecolor.
checkboxplain No TheURLoftheimageforanotselecteditem.Thiswillbe
radioboxplain usedonlywhenthetypeofthelistorofthechoicegroupis
eitherexclusiveormultiple.Defaultisasimpleimagedrawnin
thedefinedchoicecolor.Whennoneisgiven,noimagewill
bedrawnfornotselecteditems.Onlytheimageforselected
itemswillbedrawninthatcase.

Dependingonthetypeofthecorrespondinglistorchoicegroup,differentdynamicselectorsare
usedbyachoiceitem:
TypeofListor Selector
ChoiceGroup
implicit listitem
exclusive radiobox
multiple checkbox
popup popup

TheChoiceGroup
Achoicegroupcontainsseveralchoiceitems.Itsupportsthefocusedstyleattribute:
Attribute Required Explanation
focusedstyle No Thenameofthestyleforthecurrentlyfocuseditem.
columns No Thenumberofcolumns.Thiscanbeusedtolayouttheitemsin
atable.Defaultsto1column.
columnswidth No Eithernormal,equalorthewidthforeachcolumnina
commaseparatedlist(e.g.columns-width: 60,60,100;).
Defaultstonormal,meaningthateachcolumnusesasmuch
spaceasthewidestitemofthatcolumnneeds.
Theequalwidthleadstocolumnswhichhaveallthesame
width.

139
TheJ2MEPolishGUI

Attribute Required Explanation


Theexplicitlistofcolumnwidthsresultsintheusageofthose
widths.
viewtype No Theviewtypeusedforthischoicegroup.Pleasecomparethe
discussionofviewtypesonpage136.
popupimage No TheURLtotheimagewhichshouldbeshownintheclosed
popupgroup.Perdefaultasimpledropdownimagewillbe
used.
popupcolor No Thecolorforthearrowinthedropdownimageofaclosed
popupgroup.Defaultstoblack.
popupbackground No Thecolorforthebackgroundinthedropdownimageofa
color closedpopupgroup.Defaultstowhite.

AnmultipleChoiceGroupaddsthecommandsMarkandUnmarkbydefaulttothemenu.The
namesofthecommandscanbechangedeasily,comparepage76.Ifyouwanttosuppressthe
commandscompletely,thepolish.ChoiceGroup.suppressMarkCommandsvariablehastobeset:
<variable name="polish.ChoiceGroup.suppressMarkCommands" value="true"/>

ThesameholdstruefortheSelectcommand:
<variable name="polish.ChoiceGroup.suppressSelectCommand" value="true"/>

TheGauge
AGaugeshowsaprogressindicator.Itsupportsfollowingadditionalattributes:

Attribute Required Explanation


gaugeimage No TheURLoftheimage,e.g.gauge-image:
url(progress.png);.Whennogaugewidthisdefined,the
widthofthisimagewillbeusedinstead.
gaugecolor No Thecoloroftheprogressbar.Defaultstoblue.
gaugewidth No Thewidthofthegaugeelementinpixels.Whennowidthis
defined,eithertheavailablewidthorthewidthoftheprovided
imagewillbeused.
gaugeheight No Theheightofthegaugeelementinpixels.Defaultsto10.
Whenanimageisprovided,theheightoftheimagewillbe
used.
gaugemode No Eitherchunkedorcontinuous.Inthecontinuousmodeonly
thegaugecolorwillbeused,whereasthechunkedmode
intersectstheindicatorinchunks.Thesettingisignoredwhen
animageisprovided.Defaultvalueischunked.

140
TheJ2MEPolishGUI

Attribute Required Explanation


gaugegapcolor No Thecolorofgapsbetweensinglechunks.Onlyusedinthe
chunkedgaugemodeorwhenagaugewithanindefinite
rangeisused.Inthelattercasetheprovidedcolorwillbeused
toindicatetheidlestate.Defaultgapcoloriswhite.
gaugegapwidth No Thewidthofgapsinpixelsbetweensinglechunks.Onlyused
inthechunkedgaugemode.Defaultsto3.
gaugechunkwidth No Thewidthofthesinglechunksinthechunkedgaugemode.
gaugeshowvalue No Eithertrueorfalse.Determineswhetherthecurrentvalue
shouldbeshown.Thisdefaultstotrueforalldefinitegauge
items.
gaugevaluealign No Eitherleftorright.Defineswherethecurrentvalueofthe
gaugeshouldbedisplayed.Defaultstoleft,thatisleftofthe
actualgaugeitem.

Thefollowingexampleshowstheuseofthegaugeattributes:
.gaugeStyle {
padding: 2;
border-color: white;
gauge-image: url( indicator.png );
gauge-color: rgb( 86, 165, 255 );
gauge-width: 60;
gauge-gap-color: rgb( 38, 95, 158 );
/* these setting are ignored, since an image is provided:
gauge-height: 8;
gauge-mode: chunked;
gauge-gap-width: 5;
gauge-chunk-width: 10;
*/
}

WhentheGaugeitemisusedwithanindefiniterange,thegaugegapcolorwillbeusedtoindicate
theidlestate.Whenthecontinuousrunningstateisenteredandanimagehasbeenspecified,the
imagewillflyfromthelefttotherightoftheindicator.

TheTextField
ATextFieldisusedtogetuserinput.Youcanchoosewhetherthenativeinputmethodsoradirect
inputmodeshouldbeused.Whenthenativemodeisactivated,anewinputscreenwillpopupfor
theuserandspecialinputmodeslikeT9orhandwritingrecognitioncanbeused.Whenthedirect
inputmodeisusedinstead,noextrascreenwillbeshownandJ2MEPolishacceptstheentered
characterdirectly.PleasecomparethefollowingsubsectionDirectInputModeformore
information.
TheTextFieldsupportsfollowingadditionalattributes:

141
TheJ2MEPolishGUI

Attribute Required Explanation


textfieldwidth No Theminimumwidthofthetextfieldelementinpixels.
textfieldheight No Theminimumheightofthetextfieldelementinpixels.
Defaultstotheheightoftheusedfont.
textfielddirectinput No Defineswhetherthedirectinputmodeshouldbeactivated.
Possiblevaluesareeitherfalseortrue.Bydefaultthe
directinputmodeisdeactivated(false).
textfieldcaretcolor No Thecolorofthecaretwhichindicatestheeditingposition.This
defaultstothecoloroftheusedfont.
textfieldcaretchar No Thecharacterwhichindicatestheeditingposition.This
defaultsto|.
textfieldshowlength No Determineswhetherthelengthoftheenteredtextshouldbe
shownduringtheeditingofthisfield.Thishasaneffectonly
whenthedirectinputmodeisused.

ThefollowingexampleshowstheuseoftheTextFieldattributes:
.inputStyle {
padding: 2;
background-color: white;
border-color: black;
textfield-height: 15;
textfield-width: 40;
textfield-direct-input: true;
textfield-caret-color: red;
textfield-caret-char: >;
textfield-show-length: true;
}

TextFieldCommands

ATextFieldaddstheClearandDeletecommandstothemenubydefault.Thenamesofthese
commandscanbechangedeasily,comparepage76.Ifyouwanttosuppressthecommands
completely,thepolish.TextField.suppressCommandsvariablehastobeset:
<variable name="polish.TextField.suppressCommands" value="true"/>

Youcanalsodeactivatethe"Clear"commandsingly:
<variable name="polish.TextField.suppressClearCommand" value="true"/>

Lastbutnotleastitisalsopossibletodeactivatethe"Delete"commandsingly:
<variable name="polish.TextField.suppressDeleteCommand" value="true"/>

DirectInputMode

ThedirectinputmodecanbeactivatedforTextFieldsaswellasforTextBoxesusingtheCSS
attributetextfielddirectinputorbydefiningthepreprocessingvariable
polish.TextField.useDirectInputinthebuild.xmlfile:

142
TheJ2MEPolishGUI

<variable name="polish.TextField.useDirectInput" value="true"/>

Whenthedirectinputmodeisused,noextrascreenwillbeusedforeditingthetextandall
designingpossibilitiesofJ2MEPolishcanbeused.WhentheTextFieldisusedwithinaForm,the
associatedItemStateListenerwillbenotifiedaftereachchangeofthetext.
Onstylusbaseddevices,thismodeshouldnotbeusedsincethesedevicesoftenrelyonnativeinput
methodslikehandwritingrecognition.Thiscanbeensuredbysettingthepreprocessingvariable
onlyfordeviceswhichhavenopointerevents:
<variable name="polish.TextField.useDirectInput" value="true"
if="!polish.hasPointerEvents"/>

Thedirectinputshouldnotbeusedforeditinglongstexts(i.e.TextBoxes),sinceT9andsimilar
inputhelperscannotbeusedinthismode.
Theusercanchangetheinputmodefromlowercase(abc)toinitialletteruppercase(Abc)to
uppercase(ABC)andtonumeric(123).Thecurrentinputmodeisshownbelowthetitleinan
extraStringItem.ThisitemcanbedesignedusingthepredefinedCSSstyleinfo:
info {
padding-right: 10;
background: none;
border-color: black;
font-style: plain;
font-face: proportional;
font-size: small;
font-color: fontColor; /* a color defined in the colors section */
layout: right;
}

Theinfoitemcanbedeactivatedgloballybysettingthepolish.TextField.showInputInfovariable
tofalse:
<variable name="polish.TextField.showInputInfo" value="false" />

NexttousingtheCSSattributestextfieldcaretcolor,textfieldcaretcharandtextfieldshow
lengththebehaviorofthedirectinputmodecanbeadjustedusingseveralpreprocessingvariables.
Especiallytheavailablecharactercanbechanged,whichcanbenecessaryforlocalizingthedirect
input.
Followingvariablescanbeset:
Variable Default Explanation
polish.TextField.InputT 1000 Thetimeoutinmillisecondsafterwhichachosencharacter
imeout isinsertedintothetextautomatically.
polish.TextField.showI true Defineswhethertheboxshowingthecurrentinputmode
nputInfo (e.g.123,Abc,abc,ABC)shouldbeshownatall.
Youcandeactivatetheboxgloballybysettingthe
polish.TextField.showInputInfovariabletofalse.
polish.key.ChangeInput Varying Thekeywhichisusedforchangingtheinputmode
ModeKey betweenlowercase(abc),uppercase(ABC),initial

143
TheJ2MEPolishGUI

Variable Default Explanation


letteruppercase(Abc)andnumeric(123).OnSony
EricssondevicesCanvas.KEY_STAR(42),onMotorola
devicesCanvas.KEY_NUM0(48)andonallotherdevices
Canvas.KEY_POUND(35)isused.
polish.TextField.charac .,!?:/@_ Thecharacterswhichareavailablewhenthekey1is
tersKey1 +1 pressed.
polish.TextField.charac abc2 Thecharacterswhichareavailablewhenthekey2is
tersKey2 pressed.Itmightbeusefultoaddlocalspecificumlauts
here.
polish.TextField.charac def3 Thecharacterswhichareavailablewhenthekey3is
tersKey3 pressed.
polish.TextField.charac ghi4 Thecharacterswhichareavailablewhenthekey4is
tersKey3 pressed.
polish.TextField.charac jkl5 Thecharacterswhichareavailablewhenthekey5is
tersKey5 pressed.
polish.TextField.charac mno6 Thecharacterswhichareavailablewhenthekey6is
tersKey6 pressed.
polish.TextField.charac pqrs7 Thecharacterswhichareavailablewhenthekey7is
tersKey7 pressed.
polish.TextField.charac tuv8 Thecharacterswhichareavailablewhenthekey8is
tersKey8 pressed.
polish.TextField.charac wxyz9 Thecharacterswhichareavailablewhenthekey9is
tersKey9 pressed.
polish.TextField.charac 0 Thecharacterswhichareavailablewhenthekey0is
tersKey0 pressed.OnMotoroladevicesthiskeyisusedforswitching
theinputmode.
polish.TextField.charac .,!?:/@_+ Thecharacterswhichareavailablewhenthekey*is
tersKeyStar pressed.OnMotoroladevicesthiskeyisusedforentering
spaces().
polish.TextField.charac (none) Thecharacterswhichareavailablewhenthekey#is
tersKeyPound pressed.OnSonyEricssondevicesthiskeyisusedfor
enteringspaces().

TheDateField
ADateFieldisusedtoenterdateortimeinformation.Currentlytheinputisdonewiththeuseofthe
nativefunctions,sothatspecialinputmodescanbeused(likeT9orhandwritingrecognition).The
DateFieldsupportsfollowingadditionalattributes:

144
TheJ2MEPolishGUI

Attribute Required Explanation


datefieldwidth No Theminimumwidthofthedatefieldelementinpixels.
datefieldheight No Theminimumheightofthedatefieldelementinpixels.
Defaultstotheheightoftheusedfont.

Theappearanceofthedatefieldcanalsobeadjustedusingthepreprocessingvariable
polish.DateFormat,whichcanbedefinedinthe<variables>sectionoftheJ2MEPolishtask:
<variable name="polish.DateFormat" value="us" />:TheUSstandardofMMDD
YYYYisused,e.g.12242004.
<variable name="polish.DateFormat" value="de" />:TheGermanstandardof
DD.MM.YYYYisused,e.g.24.12.2004.
<variable name="polish.DateFormat" value="fr" />:TheFrenchstandardof
DD/MM/YYYYisused,e.g.24/12/2004.
Allothersettings:TheISO8601standardofYYYYMMDDisused,e.g.20041224.
TheDateFormatalsosupportsthegenericvaluesdmy(daymonthyear),mdy(monthdayyear)
orymd(yearmonthday).Alongwiththepolish.DateFormatSeparatorvariableandthe
polish.DateFormatEmptyTextvariableonecanuseanycustomdateformat:
<variable name="polish.DateFormat" value="ymd"/>
<variable name="polish.DateFormatSeparator" value="/"/>
<variable name="polish.DateFormatEmptyText" value="Select Date"/>

TheTicker
ATickerscrollsatextoverthecurrentscreen.InJ2MEPolishthetickerissituatedrightabovethe
menubaronthebottomofascreen.Followingattributeissupported:
Attribute Required Explanation
tickerstep No Thenumberofpixelsbywhichthetickerisshiftedateach
update.Defaultsto2pixels.

TheMenuBar

Inthemenubarthecommandsresidethathavebeenaddedtoascreen.Thisbarcanbedesigned
usingthepredefinedmenustyle.Thefontsettingsinthisstyleareusedtorendertheactual
commands,andtheCSSattrbutemenubar-colordefinesthecolorofthemenubar.Thecolor
canhaveanysettingincludingtransparent,whichisusefulwhenthebackgroundofthe
correspondingscreenshouldbeshown.Themenubar-colordefaultstowhitebytheway.When
thisattributeisalsodefinedinascreenstyle,itwilloverridethesettinginthemenustyleforthe
correspondingscreen.Letmedemonstrate:
menu {
padding: 5;
background: none;
/* The design of the commands in the menu-bar: */

145
TheJ2MEPolishGUI

font-style: bold;
font-face: proportional;
font-size: small;
font-color: red;
/* The color of the menubar background: */
menubar-color: black;
}

.myScreenStyle {
background-image: url( bg.png );
/* use a transparent menubar for screens with this style,
so that the bg.png image is shown in the menubar as well: */
menubar-color: transparent;
}

Whenthereismorethanoneitemavailableinthemenu,anOptionsmenuwillbeshown
automatically,whichopenstherealmenuwhenpressed(likeshowninthefollowingfigures).
Theitemsintheopenedmenuaredesignedusingthepredefinedmenuitemstyle.Thebackground
andtheborderoftheopenedmenuisdesignedusingthemenustyle.Youcanchangethenamesof
theOptions,SelectandCancelcommandsbytheway,thisisexplainedinthelocalization
chapteronpage76.

TheExtendedMenuBar
Youcanusetheextendedmenubarincaseswhenthedesignpossibilitiesofthe
normalmenubararenotsufficientforyou.Incontrasttothenormalmenubar,
theextendedmenubarisafullblownitemandcan,therefore,bedesignedjust
likeanyotheritem.Thepriceforusingtheextendedmenubaristohavean
additional2kbclassfileinyourJAR.
Forusingtheextendedmenubarinsteadofthenormalone,youneedtosetthe
"polish.MenuBar.useExtendedMenuBar"preprocessingvariableto"true"inthe
<variables>sectionofthebuild.xmlfile: Fig.6:Usingimages
intheextendedmenu
<variables>
bar.
<variable
name="polish.MenuBar.useExtendedMenuBar"
value="true"
/>
</variables>

Themenubarcanbedesignedusingthepredefinedstyles"menubar","leftcommand"and
"rightcommand":

Style Description
menubar Thisdesignofthemenubaritself.
leftcommand Designstheleftcommand("Options","Select"anduserdefined
commands).AcceptsallattributesoftheIconItem.
rightcommand Designstherightcommand("Cancel"anduserdefinedBACKor

146
TheJ2MEPolishGUI

Style Description
CANCELcommands).AcceptsallattributesoftheIconItem.

Themenubarstyleoffersfollowingadditionalattributes:

Attribute Required Explanation


menubaroptions No DefinestheimageURLfortheoptionsimageoftheextended
image menubar.
menubarselect No DefinestheimageURLfortheselectimageoftheextended
image menubar.
menubarcancel No DefinestheimageURLforthecancelimageoftheextended
image menubar.
menubarshow No Determineswhetherthetextshouldbeshownaswellinthe
imageandtext menubar,whenanimagehasbeendefinedforthe
correspondingaction.Defaultsto"false".

Thefollowingexampledemonstratesthedesignoftheextendedmenubar:
menubar {
margin-top: 0;
margin-bottom: 0;
margin-left: 2;
margin-right: 2;
padding: 0;
background: none;
menubar-options-image: url( options.png );
/*
menubar-select-image: url( checked.png );
menubar-cancel-image: url( cancel.png );
menubar-show-image-and-text: true;
*/
}

leftcommand {
padding-horizontal: 4;
padding-bottom: 0;
font-color: fontColor;
font-style: bold;
background: none;
}

rightcommand {
padding-horizontal: 4;
padding-bottom: 0;
font-color: fontColor;
font-style: bold;
background: none;
}

147
TheJ2MEPolishGUI

TheTabbedForm
ThetabbedformcanbedesignedlikeanyFormandacceptstheverysameCSSattributes.
Additionallythepredefinedstyles"tabbar","activetab"and"inactivetab"canbeusedtodesignthe
additionalelementsofatabbedform.

Style Description
tabbar ThisstyledesignsthetabbarofaTabbedForm.
activetab DesignsthecurrentlyactivetabofaTabbedForm.
inactivetab DesignsalltabsbutthecurrentlyselectedoneofaTabbedForm.

Youcansetthecolorofthescrollingindicatorwithinthetabbarstylewiththetabbarscrolling
indicatorcolorattribute:
tabbar {
background-color: white;
layout: expand;
padding-bottom: 0;
tabbar-scrolling-indicator-color: black;
}

activetab {
background-type: round-tab;
background-color: silver;
background-arc: 8;
font-color: white;
padding-left: 10;
padding-right: 8;
}

inactivetab {
padding-left: 6;
padding-right: 4;
margin-left: 2;
margin-right: 2;
background-type: round-tab;
background-color: gray;
background-arc: 8;
font-color: silver;
}

148
TheMIDP/2.0CompatibleGameEngine

TheMIDP/2.0CompatibleGameEngine
EventhoughMIDP/2.0isthefuture,themarketiscrowdedwithMIDP/1.0devices.J2MEPolish
offersaniftysolutionforthosedeveloperswhowanttosupportbothplatformswiththeadvanced
MIDP/2.0technology.
Allclassesofthejavax.microedition.lcdui.gamepackagecanbeusednormally:
Class Explanation
GameCanvas TheGameCanvasclassprovidesthebasisforagameuserinterface.
Layer ALayerisanabstractclassrepresentingavisualelementofagame.
LayerManager TheLayerManagermanagesaseriesofLayers.
Sprite ASpriteisabasicvisualelementthatcanberenderedwithoneofseveral
framesstoredinanImage;differentframescanbeshowntoanimatethe
Sprite.
TiledLayer ATiledLayerisavisualelementcomposedofagridofcellsthatcanbe
filledwithasetoftileimages.

WiththisgameengineitispossibletoprogramagamewithonesourcecodeforMIDP/2.0aswell
asMIDP/1.0deviceswithoutchanginganythingwithinthesourcecode!

HowItWorks
TheJ2MEPolishbuildtoolidentifiestheusageoftheMIDP/2.0gameAPIandweavesthe
necessarywrapperclassesintothecode.Theobfuscationstepthenremovesallunnecessary
functionalitytoensurethatonlytheneededpartsareactuallyincludedintotheapplication.The
J2MEPolishgameengineonlyneedsabout5to6kbextraspaceintheresultingJARpackage,
whenallclassesareused.

Limitations
Fortechnicalreasonsthecollisiondetectionworksonlywithcollisionrectangles,whichshouldbe
settightlyforSpritestherefore.Apixellevelcollisiondetectionisnotsupported.
WhenaclassextendstheGameCanvasclass,itshouldcallthesuperimplementations,whenoneof
themethodskeyPressed(int),keyReleased(int)orkeyRepeated(int)isoverridden.
ThetransformationofSpritesiscurrentlyonlysupportedforNokiadevices,otherwisethe
transformationswillbeignored.

Optimizations
TheTiledLayerandtheGameCanvasimplementationshaveseveraloptionaloptimizations,which
canbetriggeredbydefiningspecificvariablesinthebuild.xmlfile(comparethevariablessection
onpage52).

149
TheMIDP/2.0CompatibleGameEngine

UsingaFullscreenGameCanvas
TheGameCanvasnormallyusesthefullscreenattributeofthe<build>elementtodetermine
whetheritshoulduseafullscreencanvas(comparepage36).Thisbehaviorcanbeoverriddenwith
definingthepolish.GameCanvas.useFullScreenvariable.Allowedvalueareyes,noand
menu.Pleasenotethatthemenumode(whichshouldbeusedwhencommandsareaddedtothe
GameCanvas)isonlysupportedwhentheJ2MEPolishGUIisused.Anotherlimitationofthe
menumodeisthatthepaint()methodoftheGameCanvascannotbeoverridden.

Variable Explanation
polish.GameCanvas.useFullSc Defineswhetherthefullscreenmodeisused,overridesthe
reen fullscreenattributeofthe<build>element.Possiblevaluesare
yes,noormenu.

ThefollowingexampleenablesthefullscreenmodefortheGameCanvas:
<variable name="polish.GameCanvas.useFullScreen" value="yes" />

Thisexampleshowshowtooverridethepaint()method,eventhoughtheJ2MEPolishGUIandthe
menufullscreenmodeisused:
public class MyGameCanvas extends GameCanvas {
...
//#if polish.usePolishGui && polish.classes.fullscreen:defined
//# public void paintScreen( Graphics g)
//#else
public void paint( Graphics g)
//#endif
{
// implement the paint method
...
}
}

BackbufferOptimizationfortheTiledLayer
Thebackbufferoptimizationusesabuffer,towhichthetilesareonlypaintedwhentheyhave
changed.Thiscanresultinasignificanthigherframespersecondthroughput,sincethecomplete
layerneedstobepaintedonlyseldomly.
Thedrawbackofthebackbufferoptimizationisthatitusesmorememoryandthatnotransparent
tilescanbeused.Sowhenmemoryisanissueorwhenthetiledlayerisnotusedasthebackground,
itisrecommendednottousethebackbufferoptimization.

Variable Explanation
polish.TiledLayer.useBackBuff Defineswhetherthebackbufferoptimizationshouldbeused,
er needstobetruetoenabletheoptimization.
polish.TiledLayer.Transparent Thecolorwhichisusedfortileswhichshouldtransparent.This

150
TheMIDP/2.0CompatibleGameEngine

Variable Explanation
TileColor defaultstoblack.

Thefollowingexampleenablesthebackbufferoptimization:
<variable name="polish.TiledLayer.TransparentTileColor" value="0xD0D000" />
<variable name="polish.TiledLayer.useTileBackBuffer" value="true" />

SplittinganImageintoSingleTiles
Atiledlayercanbedrawnsignificantlyfasterwhenthebaseimageissplitintosingletiles.This
optimizationneedsabitmorememorycomparedtoabasictiledlayer.Alsothetransparencyoftiles
islostwhenthedevicedoesnotsupporttheNokiaUIAPI(allNokiadevicesdosupportthisAPI).

Variable Explanation
polish.TiledLayer.splitImage DefineswhetherthebaseimageofaTiledLayershouldbesplit
intosingletiles.Needstobetruetoenablethisoptimization.

Thefollowingexampleenablesthesingletilesoptimization:
<variable name="polish.TiledLayer.splitImage" value="true" />

DefiningtheGridTypeofaTiledLayer
TheJ2MEPolishimplementationusesabytegrid,whichsignificantlydecreasethememory
footprint,butwhichalsolimitsthenumberofdifferenttilesto128.Forcaseswheremoredifferent
tilesareused,onecandefinethetypetoeitherint,shortorbyte.
Variable Explanation
polish.TiledLayer.GridType DefinesthetypeoftheusedgridinTiledLayer.Thisdefaultsto
byte.Possiblevaluesareint,shortorbyte.

Thefollowingexampleusesashortgrid,whichallowstheusageof32767differenttilesinsteadof
128differenttiles:
<variable name="polish.TiledLayer.GridType" value="short" />

UsingtheGameEngineforMIDP/2.0Devices
YoucanusetheJ2MEPolishimplementationforMIDP/2.0devicesaswell.Thiscanmakesense
becausesomevendorimplementationsarebuggyorhavesluggishperformance.Whenthegame
engineshouldbeusedforMIDP/2.0devicesaswell,youneedtodefinethepreprocessingvariable
polish.usePolishGameApi:

151
TheMIDP/2.0CompatibleGameEngine

Variable Explanation
polish.usePolishGameApi DefineswhethertheJ2MEPolishgameengineshouldbeusedon
MIDP/2.0devicesaswell.Possiblevaluesaretrueorfalse.

ThefollowingexampleusesthegameengineforNokiaMIDP/2.0devicesaswell:
<variable name="polish.usePolishGameApi" value="true" if="polish.vendor ==
Nokia" />

PortingaMIDP/2.0GametoMIDP/1.0Platforms

BuildingtheExistingApplication
InthefirststepweuseJ2MEPolishforbuildingthegame.Weneedtocopyandadjustthe
build.xmlfilefromtheprovidedsampleapplicationofJ2MEPolishandwemightneedtoadjust
thehandlingofresources.

Adjustingthebuild.xml
Tobuildtheexistinggameweneedtocopythesamplebuild.xmlfile,whichresidesinthe
samplesubdirectoryoftheJ2MEPolishinstallation,intothetherootdirectoryofthegame.
Thebuild.xmlincludesallthenecessaryinformationabouttheprojectliketheMIDletclasses,the
targetdevices,theversionofthegameandsoon.ManyIDEssupportsyntaxhighlightingandauto
completionforthisfile,butitcanalsobeeditedwithanydecenttexteditor.
TheJ2MEPolishtaskisdividedin3subsections:<info>,<deviceRequirements>and<build>.
The<info>sectioncontainsgeneralinformationabouttheproject:
<info
license="GPL"
name="J2ME Polish"
version="1.3.4"
description="A sample project"
vendorName="Enough Software"
infoUrl="http://www.j2mepolish.org"
icon="dot.png"
jarName="${polish.vendor}-${polish.name}-example.jar"
jarUrl="${deploy-url}${polish.jarName}"
copyright="Copyright 2004 Enough Software. All rights reserved."
deleteConfirm="Do you really want to kill me?"
/>
Thisinformationcanbechangedarbitrarily.Thenameoftheapplicationcanalsocontainthename
andvendorofthetargetdevice.Theaboveexample${polish.vendor}${polish.name}
example.jarresultsinthenameNokia6600example.jar,whentheapplicationisbuildforthe
Nokia/6600deviceforexample.Theaboveproperty${deploy-url}isdefinedaboveinthe
samplebuild.xmlscriptandisusuallyempty.
Inthefollowing<deviceRequirements>sectionthetargetdevicesareselected.Sincewewantto
buildtheapplicationforaMIDP/2.0devicefirst,weenteranyMIDP/2.0capabledeviceintothe
requirements,e.g.Nokia/6600orNokia/Series60Midp2.TheSeries60Midp2deviceisa

152
TheMIDP/2.0CompatibleGameEngine

virtualdevicerepresentingatypicalSeries60phonewithMIDP/2.0support.Suchisphone
supportsadditionallytheMobileMediaAPI(mmapi)andtheWirelessMessagingAPI(wmapi).
ThedeviceselectionisveryflexibleandcanselectallMIDP/2.0deviceswhichsupporttheMobile
MediaAPIaswell,forexample.Forkeepingthisexampleeasytomanage,weuseonlytheselection
bythedevice'sidentifier:
<deviceRequirements>
<requirement name="Identifier" value="Nokia/Series60Midp2" />
</deviceRequirements>

The<build>sectioncontrolstheactualbuildprocess.Forkeepingthisexampleeasy,wechoosenot
tousetheGUIofJ2MEPolishandsettheusePolishGuiattributetofalse.Wealsoneedto
adjustthe<midlet>subelementandenterthefullnameofourgameclass:
<build
usePolishGui="false"
resDir="resources"
workDir="${dir.work}"
>
<!-- midlets definition -->
<midlet class="de.enough.polish.example.MenuMidlet" name="Example" />
</build>

The<build>sectionhasmanysubelementsandcanautomatemanytasksfromtheinclusionofthe
debuggingframeworktothesigningoftheapplication.Thesesettingsareoutsideofthescopeor
thisarticle,though.

ManagingtheResources
J2MEPolishmanagestheinclusionofresourcesautomaticallyforyou.Justcopyallresources
whichareneededinanycaseintotheresourcesfolderofyourproject(createitfirstif
necessary).
Youcanthenusethesubfoldersforincludingresourcesonlyfordeviceswhichcanusethese
resources.ForexampleyoucanplaceMIDIsoundfilesintotheresources/midifolderand3gpp
videofilesintotheresources/3gppfolder.Thisresultsinsmallerapplicationbundles,since
unnecessaryresourceswillnotbeincludedatall.
Morespecificresourcesareincludedinsteadofgeneralresources.Youcouldkeeplowcolorimages
intothegeneralresourcesfolderandusetheresources/BitsPerPixel.16+folderforusing
highcolorversionsoftheseimagesfordeviceswhichsupportatleast16bitsperpixel(65.536
colors).Thesameprinciplecanbeusedforincludingspecificresourcesforalldevicesofaspecific
vendor(e.g.resources/Sony-Ericssonorresources/Nokia)orevenforspecificdevices
(e.e.resources/Nokia/6600).
ThispowerfulautomaticresourceassemblingofJ2MEPolishisthereasonwhynosubfolderscan
beusedwithintheapplicationcode.Allresourcesarecopiedintothebasefolderoftheapplication.
SoinsteadofImage.createImage("images/sprite.png")youneedtouse
Image.createImage("sprite.png")withinthesourcecode.Thishastheextrabenefitofsaving
spacewithinthefinaljarfileaswellasheapsizeinthegame.

153
TheMIDP/2.0CompatibleGameEngine

BuildingtheGame
NowallsettingsnecessaryforbuildingthegamewithJ2MEPolishhavebeenmade,sonowcall
antonthecommandlinefromwithinthebasefolderorwecanrightclickthebuild.xmlfile
withintheIDEandselectRunAnt,makeorsimilar.
J2MEPolishwillnowpreprocess,compile,obfuscate,preverifyandpackagethegame
automatically.Whentheabovesettingswillbeused,wewillfindthefilesNokia-
Series60Midp2-example.jarandNokia-Series60Midp2-example.jadinthedistfolder
oftheprojectafterthebuild.
Thegameshouldnowbetestedwithanemulatororareal
ChecklistforPorting
device,tomakesureeverythingworksasexpected.
Allresourcesneedstobeloaded
PortingtheGametoMIDP/1.0 fromthebasedirectory,e.g.
Image.createImage(/sprite.png)
AfterthesuccessfultransitiontoJ2MEPolish,portingagame Useimportstatementsinsteadof
toMIDP/1.0isveryeasy. fullqualifiedclassnamesinthe
sourcecode
NecessarySourceCodeChanges Usepreprocessingforadjusting
thesourcecodetospecific
SubclassesofGameCanvasneedtocallthesuper
devices,e.g.
implementationsofanyoverriddenkeyPressed(int)and //#ifpolish.midp2||
keyReleased(int)methods,sothattheJ2MEPolishgame polish.api.mmapi
engineknowsaboutthesekeys. Usetheautomaticresource
Whenthereisacompileerrorstatingthata assemblingforusingspecific
resourcesforthetargetdevices.
javax.microedition.lcdui.gameclasscannotbefound,
Settightcollisionrectangles,
pleaseensurethatyouuseimportstatementsratherthanfully
sincepixellevelcollision
qualifiedclassnamesinyoursourcecode: detectioncannotbeusedon
InsteadofMyGameCanvas extends MIDP/1.0devices
javax.microedition.lcdui.game.GameCanvas the Spritetransformationsareonly
import-statement is needed: supportedfordeviceswhich
supportNokia'sUIAPI,so
import javax.microedition.lcdui.game.GameCanvas; transformedPNGsneedtobe
MyGameCanvas extends GameCanvas
usedforotherdevices.
WorkingAroundtheLimitationsoftheGameEngine Thesuperimplementationof
keyPressed()andkeyReleased()
PixelLevelCollisionDetection shouldalwaysbecalledfirst,
whensuchmethodsare
PixellevelcollisiondetectioncannotbeusedonMIDP/1.0 overridden.
platforms,soweneedtosettightcollisionrectanglesforthe
sprites.

SpriteTransformations

AnotherlimitationofJ2MEPolishisthatspritetransformationsareonlysupportedforNokia
devicessofar.Thismeansthatforotherdevicestransformedspriteimagesareneeded.Thesecanbe
easilyincludedbyputtingthemintheresources/NoSpriteTransformationsfolder.Wecan
adjustthehandlingofspritetransformationsbyusingthepreprocessingofJ2MEPolish:
//#if !(polish.midp2 || polish.supportSpriteTransformation)

154
TheMIDP/2.0CompatibleGameEngine

private final static int MIRROR_SEQUENCE = new int[]{3,4,7,5};


//#endif
[...]
//#if polish.midp2 || polish.supportSpriteTransformation
this.sprite.setTransform( Sprite.TRANS_MIRROR );
//#else
this.sprite.setFrameSequence( MIRROR_SEQUENCE );
//#endif

Intheaboveexampleweusecallthetransform(int)methodofthespriteonlywhenthedeviceeither
usestheMIDP/2.0platformorsupportsspritetransformation.Otherwisetheframesequence
MIRROR_SEQUENCEwillbeusedinstead.
Asimilaradjustmentcanbeneededduringtheinstantiationofthesprite,whenthetransformed
imagehasdifferentframedimensions:
//#if polish.midp2 || polish.supportSpriteTransformation
int frameWidth = 10;
int frameHeight = 8;
//#else
//# int frameWidth = 6;
//# int frameHeight = 8;
//#endif
this.sprite = new Sprite( spriteImage, frameWidth, frameHeight );

Foranevenmoreflexibleapproachyoucanusepreprocessingvariables.Thesevariablescanbe
definedinthe<variables>subelementofthebuild.xml file:
<variables>
<variable
name="player.frameDimensions"
value="10, 8"
if="polish.supportSpriteTransformation || polish.midp2"
/>
<variable
name="player.frameDimensions"
value="6, 8"
unless="polish.supportSpriteTransformation || polish.midp2"
/>
<variable
name="player.frameDimensions"
value="6, 6"
if="polish.identifier == Nokia/7210"
/>
</variables>

Intheaboveexampletheframedimensionsaresetto10x8fordeviceswhichsupporteitherthe
MIDP/2.0orthespritetransformation.Thedimension6x8areusedforallotherdevices.Forthe
Nokia/7210phonethespecialvalueof6x6isused.
Inthesourcecodeadefaultvalueshouldalwaysbeusedforcasesinwhichthevariablesarenotset:
//#if player.frameDimensions:defined
//#= this.sprite = new Sprite( spriteImage, ${player.frameDimensions} );
//#else
this.sprite = new Sprite( spriteImage, 10, 8 );
//#endif

Byusingthisapproachtheresourcescanlaterbechangedwithoutneedingtochangethesource

155
TheMIDP/2.0CompatibleGameEngine

code.

UsingPreprocessingforDeviceSpecificAdjustments
YoucanuseJ2MEPolish'spreprocessingcapabilitiesforfurtheradjustmentsofthegame.Atypical
situationisthattheMMAPIisusedforsoundplayback.NotallMIDP/1.0phonesdosupportthis
APIhowever.InthesecasestheMMAPIcodeneedstobehiddenfromsuchdevices:
//#if polish.midp2 || polish.api.mmapi UsefulPreprocessingSymbols
// ...
polish.supportSpriteTra
Player audioPlayer = Manager.createPlayer
( inputStream, "audio/midi" ); nsformationindicatesthat
// .... MIDP/1.0Spritetransformations
//#elif polish.api.nokia-ui aresupportedforthecurrent
// ... device.
Sound sound = new Sound( data,
Sound.FORMAT_WAV ); polish.api.mmapiisdefined
// ... whentheMobileMediaAPIis
//#endif supportedbythecurrentdevice.
polish.api.nokia-uiis
YoumightneedtoadjusttheGUIaswell.Whenyouareusing definedwhentheNokiaUIAPI
issupportedbythecurrent
J2MEPolish'sadvancedGUI,youcanevenuseMIDP/2.0
device.
featureslikeCustomItemsandItemCommandListeneron
polish.midp1 /
MIDP/1.0devices.WhentheJ2MEPolish'sGUIisnotused, polish.midp2indicatesthe
however,anyMIDP/2.0GUIcodeneedstobehiddenfromthe currentMIDPplatform.
MIDP/1.0game: polish.cldc1.0 /
//#if polish.midp2 || polish.usePolishGui polish.cldc1.1indicatesthe
MyCustomItem item = new MyCustomItem(); currentconfiguration.
this.form.append( item );
//#endif
polish.usePolishGuiis
enabledwhentheGUIofJ2ME
Polishisused.
Anothercommonissueistheusageofafullscreenmode.The
setFullScreenMode(boolean)methodoftheCanvasclassisonlyavailableonMIDP/2.0devices.
ForMIDP/1.0devices,thefullscreenmodecanbeactivatedbydefiningthepreprocessingvariable
polish.GameCanvas.useFullScreen(seebelow),butthesetFullScreenMode(boolean)
methodcanstillbeusedforMIDP/2.0devices:
//#if polish.midp2
setFullScreenMode( true );
//#endif

Youcanuseamultitudeofpreprocessingsymbolsandvariables.Whichoftheseareavailable
dependsonthedeviceandthecurrentsetup.PleasecompareJ2MEPolish'sdevicedatabaseandthe
preprocessingdocumentationonpage78forfurtherinformation.

156
ExtendingJ2MEPolish

ExtendingJ2MEPolish
J2MEPolishcanbeextendedquitesimplyandinseveralways.
BuildTools:
Obfuscator:integrateyourown(orathirdparty)obfuscator
Preprocessing:addyourownpreprocessingdirectives
Youcanalsousethe<java>elementtoextendJ2MEPolish
GUI:
BackgroundsandBorders:custombordersorbackgroundsenhancethepossibilities
Items:extendandusestandardCustomItemsanddesignthemusingCSS
The<java>elementisdescribedonpage59,whereastheotherextensionsarediscussedinthis
chapter.

IntegratingaCustomObfuscator
Forintegratinganotherobfuscator,youneedtofirstcreateaclasswhichextendsthe
de.enough.polish.obfuscate.Obfuscatorclass.Secondlyyouneedtointegrateyourobfuscatorinthe
build.xmlfile.

Preparations
CreateanewprojectinyourIDEandsettheclasspathsothatitincludestheenoughj2mepolish
build.jar,whichcanbefoundintheimportfolderoftheinstallationdirectory.Alsoincludethe
ant.jarfilefromyourAntinstallationintotheclasspath.

CreatingtheObfuscatorClass
Createanewclasswhichextendsde.enough.polish.obfuscate.Obfuscatorandimplementthe
obfuscatemethod:
/**
* Obfuscates a jar-file for the given device.
*
* @param device The J2ME device
* @param sourceFile The jar-file containing the projects classes
* @param targetFile The file to which the obfuscated classes should be copied to
* @param preserve All names of classes which should be preserved,
* that means not renamed or removed.
* @param bootClassPath A path to the library containing either the MIDP/1.0
* or MIDP/2.0 environment.
* @throws BuildException when the obfuscation failed
*/
public abstract void obfuscate( Device device,
File sourceFile,
File targetFile,
String[] preserve,
Path bootClassPath )
throws BuildException;

Youcanmakeuseoffollowingprotectedvariables:

157
ExtendingJ2MEPolish

de.enough.polish.LibraryManagerlibraryManager:amanagerfordeviceAPIs
java.io.FilelibDir:thepathtotheimportfolder
org.apache.tools.ant.Projectproject:theAntprojectinwhichtheobfuscatorisembedded
Ifyouneedfurtherconfigurationsettings,youcanaddthemwiththe<parameter>construct,which
isdiscussedbelow.
Tocalltheobfuscator,youtypicallyneedtoaccomplishthesetasksintheobfuscatemethod:
1. Settheclasspathforthegivendevice:YoucangetthedevicespecificAPIsbycalling
device.getClasspath() whichreturnsaStringarraycontainingthelocationsofthedevice
APIJars.TheusualbehavioristosettheclasspathfortheobfuscatortothegivenbootClassPath
andthedevicespecificAPIs.
2. Specifywhichclassesshouldbesparedfromobfuscation:theclassesspecifiedbythepreserve
arrayshouldnotbeobfuscatedatall.ThesealwaysincludetheMIDletclassesandmaybesome
otherclasseswhichareloadedwiththeClass.forName()mechanism.
3. Starttheobfuscator:settheinputtotheprovidedsourceFileandtheoutputtothespecified
targetFile.BothofthesefilesareJars.
Whenthereisanexception,abortthebuildbythrowingaorg.apache.tools.ant.BuildException
explainingthedetailswhytheobfuscationwasaborted.

IntegratingtheObfuscatorintothebuild.xml
Youcanintegrateanythirdpartyobfuscatorwiththeusual<obfuscator>elementinthebuild.xml
file(comparepage48).
<obfuscator unless="test" enable="true"
class="com.company.obfuscate.MyObfuscator"
classPath="../obfuscator-project/bin/classes"
>
<keep class="com.company.dynamic.SomeDynamicClass" />
<keep class="com.company.dynamic.AnotherDynamicClass" />
<parameter name="scriptFile" value="../scripts/obfuscate.script" />
</obfuscator>

Theclassattributeneedstobesettothenewclass.TheclassPathattributecanbeusedfor
pointingoutthelocationoftheobfuscator.Thisisonlyneededwhentheobfuscatorisnotonthe
Antclasspath.

ConfiguringtheObfuscatorwithParameters
Theobfuscatorcanbeconfiguredusing<parameter>subelementsinthebuild.xml.Foreach
<parameter>acorrespondingset[parametername]methodneedstobeimplemented,whicheither
needstohaveoneFileparameter,onebooleanoroneStringparameter:
<parameter name="scriptFile" value="../scripts/obfuscate.script" />

Fortheusingtheaboveparameter,theobfuscatorneedstoimplementeitherthepublicmethod
setScriptFile( File file )orthepublicmethodsetScriptFile( String value ).Whena
methodwithaFileparameterisused,relativefilepathsareresolvedrelativetothelocationofthe
build.xmlfile(ortobemorepreciserelativetotheproject.getBaseDir()location).Thefilegivenas

158
ExtendingJ2MEPolish

aparameterinthesetmethodusesanabsolutepathinthatcase.

CreatingandUsingCustomPreprocessingDirectives
Youcaneasilyuseyourownpreprocessingdirectivesbyextendingthe
de.enough.polish.preprocess.CustomPreprocessorclassandbyintegratingyourpreprocessorwith
the<preprocessor>elementinthebuild.xmlfile.

Preparations
CreateanewprojectinyourIDEandsettheclasspathsothatitincludestheenoughj2mepolish
build.jar,whichcanbefoundintheimportfolderoftheinstallationdirectory.Alsoincludethe
ant.jarfilefromyourAntinstallationintotheclasspath.

CreatingthePreprocessorClass
Createanewclasswhichextendsde.enough.polish.preprocess.CustomPreprocessor.

UsingtheregisterDirective()Method
TheeasiestwaytousecustomdirectiveisbyregisteringthemwiththeregisterDirectivemethod:
/**
* Adds a directive which is searched for in the preprocessed source codes.
* Whenever the directive is found, the appropriate method
* process[directive-name] is called.
* When for example the preprocessing directive "//#hello" should be processed,
* the subclass needs to implement the method
* processHello( String line, StringList lines, String className ).
* <pre>
* registerDirective("hello");
* // is the same like
* registerDirective("//#hello");
* </pre>
*
* @param directive the preprocessing directive which should be found.
* The directive needs to contain at least 2 characters (apart from
* the beginning "//#").
* The "//#" beginning is added when not specified.
* @throws BuildException when the corresponding method could not be found.
*/
protected void registerDirective( String directive ) throws BuildException

Whenforexamplethedirectivedateisregistered,thepublicmethodprocessDate( String
line, de.enough.polish.util.StringList lines, String className ) needstobe
implemented.
Youcanmakeuseoffollowingprotectedvariables:
de.enough.polish.preprocess.Preprocessorpreprocessor:themainpreprocessor
de.enough.polish.preprocess.BooleanEvaluatorbooleanEvaluator:anevaluatorforcomplex
termswhichcanbeusedinthe#ifdirective.
Ifyouneedfurtherconfigurationsettings,youcanaddthemwiththe<parameter>construct,which
isdiscussedbelow.
Intheprocessingmethodthelineinwhichthepreprocessingdirectivewasfoundisusually

159
ExtendingJ2MEPolish

changed.Whenthelineischanged,pleasemakesurethatthepreprocessingdirectiveisberemoved
fromthechangedline,sothatthefollowingpreprocessingcancontinuewithouterrors.
Whenthereisanexception,abortthebuildbythrowingaorg.apache.tools.ant.BuildException
explainingthedetailswhythepreprocessingwasaborted.
ThisexampleshouldillustratetheusageoftheregisterDirective()method:
package com.company.preprocess;

import org.apache.tools.ant.BuildException;
import de.enough.polish.preprocess.CustomPreprocessor;
import de.enough.polish.util.StringList;
import java.util.Date;

public class MyPreprocessor extends CustomPreprocessor {

public MyPreprocessor() {
super();
registerDirective("date");
}

public void processDate( String line, StringList lines, String className ) {


int directiveStart = line.indexOf( "//#date");
String argument = line.substring( directiveStart + "//#date".length() ).trim();
int replacePos = argument.indexOf("${date}");
if (replacePos == -1) {
throw new BuildException(className + " at line "
+ (lines.getCurrentIndex() + 1)
+ ": Unable to process #date-directive: found no ${date} sequence in line ["
+ line + "." );
}
String result = argument.substring(0, replacePos )
+ ( new Date().toString() )
+ argument.substring( replacePos + "${date}".length() );
lines.setCurrent(result);
}
}

UsingtheprocessClass()Method
Formorecomplexsituations,youcanoverridetheprocessClass()methodwhichallowsyouto
processthewholejavafileinonego:
/**
* Processes the given class.
*
* @param lines the source code of the class
* @param className the name of the class
*/
public void processClass( StringList lines, String className ) {
while (lines.next()) {
String line = lines.getCurrent();
// now process the line...
}
}

IntegratingthePreprocessorintothebuild.xml
Youcanintegrateyourpreprocessorwiththeusual<preprocessor>elementinthebuild.xmlfile
(comparepage58).
<preprocessor

160
ExtendingJ2MEPolish

class="com.company.preprocess.MyPreprocessor"
classPath="../preprocessor-project/bin/classes"
>
<parameter name="scriptFile" value="../scripts/preprocess.script" />
</preprocessor >

Theclassattributeneedstobesettothenewclass.TheclassPathattributecanbeusedfor
pointingoutthelocationofthepreprocessor.Thisisonlyneededwhenthepreprocessorisnoton
theAntclasspath.

ConfiguringthePreprocessorwithParameters
Thepreprocessorcanbeconfiguredusing<parameter>subelementsinthebuild.xml.Foreach
<parameter>acorrespondingset[parametername]methodneedstobeimplemented,whicheither
needstohaveoneFileparameter,onebooleanoroneStringparameter:
<parameter name="scriptFile" value="../scripts/obfuscate.script" />

Fortheusingtheaboveparameter,thepreprocessorneedstoimplementeitherthepublicmethod
setScriptFile( File file )orthepublicmethodsetScriptFile( String value ).Whena
methodwithaFileparameterisused,relativefilepathsareresolvedrelativetothelocationofthe
build.xmlfile(ortobemorepreciserelativetotheproject.getBaseDir()location).Thefilegivenas
aparameterinthesetmethodusesanabsolutepathinthatcase.

ExtendingtheJ2MEPolishGUI

UsingCustomItems

YoucanintegratecustomitemstoJ2MEPolishbyextendingthe
javax.microedition.lcdui.CustomItemclass.

Initialisation
J2MEPolishcallsthegetPrefContentWidth()methodfirstwithanopenheight(1).Thenthe
getPrefContentHeight()methodiscalledwiththeactualgrantedwidth.Whenthewidthhadtobe
adjusted,thecustomitemwillbenotifiedagainwiththesetSize(width.height)method.
PleasenotethattheDisplay.getColor(int)andFont.getFont(int)areonlyavailableonMIDP/2.0
devices.Suchcallsshouldbesurroundedby#ifdefdirectives:
//#ifdef polish.midp2
Font font = Font.getFont( Font.FONT_STATIC_TEXT );
//#else
//# Font font = Font.getDefaultFont();
//#endif

InteractionModes
TheJ2MEPolishimplementationsupportstheinteractionmodesKEY_PRESS,
TRAVERSE_HORIZONTALandTRAVERSE_VERTICAL.

Traversal
Whenthecustomitemgainsthefocusforthefirsttime,thetraversemethodwillbecalledwiththe
CustomItem.NONEdirection.Subsequentcallswillincludethedirection(eitherCanvas.UP,

161
ExtendingJ2MEPolish

DOWN,LEFTorRIGHT).

UsingCSSforDesigningtheCustomItem
WhentheCSSstylesshouldbeusedfordesigningtheCustomItem,pleasemakesurethatthe
projectclasspathcontainstheenoughj2mepolishclient.jar,whichcanbefoundintheimport
folderoftheJ2MEPolishinstallationdirectory.
WhentheJ2MEPolishGUIisused,thepreprocessingsymbolpolish.usePolishGuiisdefined.
ThiscanbeusedwhentheCustomItemshouldbeusedintheJ2MEPolishGUIaswellinaplain
MIDP/2.0basedUI:
//#ifdef polish.usePolishGui
import de.enough.polish.ui.*;
//#endif

ThereareseveralwaystointegrateaCSSstyleintotheCustomItem:
1. Definingastaticstylebeforethesuperconstructoriscalled:
public MyItem( String label ) {
//#style myitem
super( label );
}
2. Allowingthesettingofthestyleinasecondconstructor:
//#ifdef polish.usePolishGui
public MyItem( String label, Style style ) {
super( label, style );
}
//#endif
3. Specifyingthenameofthedynamicstyle:
//#ifdef polish.useDynamicStyles
protected String createCssSelector() {
return "myitem";
}
//#endif

Thesecondvariantisthemostflexibleoneandisencouraged,therefore.WhentheitemMyItemis
nowusedwithinthecode,theappropriatestylecanspecifiedwiththe#styledirective:
//#style coolStyle
MyItem coolItem = new MyItem( label );

Forreadingthespecificstylesettings,themethodsetStyle(Style)needstobeoverridden:
//#ifdef polish.usePolishGui
public void setStyle( Style style ) {
//#if true
// the super-call needs to be hidden:
//# super.setStyle( style );
//#endif
this.font = style.font;
this.fontColor = style.fontColor;
// now read specific attributes:
//#ifdef polish.css.myitem-color
Integer colorInt = style.getIntProperty( "myitem-color" );
if (colorInt != null) {

162
ExtendingJ2MEPolish

this.color = colorInt.intValue();
} else {
this.color = 0xFF0000;
}
//#else
this.color = 0xFF0000;
//#endif
}
//#endif

ThesetStyle()methodwillbecalledbeforethepreferredcontentwidthandheightisrequested,
whentheCustomItemhasastyleassociatedwithit.
Pleasenotethatthevariableneedstobecalledstyleorneedstoendwithstyle,sothatJ2ME
Polishcanprocessallstylescorrectly.Thisisrequired,sinceinsteadofStringbasedattributenames
numericalshortvalueswillbeusedintheactualcode.Thisapproachsignificantlyreducesthe
runtimeperformanceandminimizestheheapusage.
Thereare3differentwaystoretrieveapropertyfromastyle:
style.getProperty( String name )returnseitheraStringrepresentingthatvalueornull
whenthepropertyisnotdefined.
style.getIntProperty( String name )returnseitheranIntegerrepresentingthatvalueor
nullwhenthepropertyisnotdefined.Youcanusethismethodonlywhenyouhaveregistered
thecorrespondingattributeinthefilecustom-css-attributes.xml.Theattributetypeneedsto
beeitherintegerorcolor.
style.getBooleanProperty( String name )returnseitheraBooleanrepresentingthatvalue
ornullwhenthepropertyisnotdefined.Youcanusethismethodonlywhenyouhaveregistered
thecorrespondingattributeinthefilecustom-css-attributes.xml.Theattributetypeneedsto
beboolean.

RegisteringCustomCSSAttributes

Youwillfindthecustomcssattributes.xmlfileintheinstallationdirectoryofJ2MEPolish.This
filecanbeusedtoregisterCSSattributeswhichareusedinyourCustomItems.
Theregistrationoftheseattributesisonlyrequiredwheneitherthestyle.getIntProperty(
String name )- orthestyle.getIntProperty( String name )methodisusedinthe
setStyle( Style )methodoftheCustomItem.Theregistrationisencouragednevertheless,since
futureversionsofJ2MEPolishmightusethisinformationforanembeddedCSSeditor.
Eachattributeisrepresentedbyan<attribute>elementwithfollowingattributes:

Attribute Required Explanation


name Yes Thenameoftheattribute,e.g.iconimage.
description No Adescriptionofthisattribute.
type No Thetypeoftheattribute.Eitherstring,integer,color,
booleanorstyle.Defaultstostring.Whenthe
getIntProperty()methodisused,thetypeneedstobeeither

163
ExtendingJ2MEPolish

Attribute Required Explanation


integerorcolor.WhenthegetBooleanProperty()methodis
used,thetypeneedstobeboolean.
appliesTo No Acommaseparatedlistofclassnamesforwhichthisattribute
canbeapplied.
default No Thedefaultvalueofthisitem.
values No Acommaseparatedlistofallowedvaluesforthisattribute.

Thefollowingexampledefinesasimpleattribute:
<attribute
name="focused-style"
type="style"
appliesTo="Screen, Form, List, ChoiceGroup"
description="The name of the style for the currently focused item."
default="focused"
/>

BackgroundsandBorders
BackgroundandbordersettingswillbeenforcedbyJ2MEPolish,theCustomItemmerelyneedsto
paintitscontents.Itisadvisable,therefore,thatabackgroundisonlypainted,whentheJ2ME
PolishGUIisnotused:
//#ifndef polish.usePolishGui
// draw default background:
g.setColor( this.backgroundColor );
g.fillRect( 0, 0, this.width, this.height );
//#endif

AddingaCustomBackground
Foraddinganewbackground,pleasecreateanewprojectcalledbackgroundprojectandmake
surethatthefilesenoughj2mepolishbuild.jar,enoughj2mepolishclient.jarandthe
midp2.jarareontheclasspathoftheproject.Thesefilescanbefoundintheimportfolderof
theJ2MEPolishinstallationdirectory.
Eachbackgroundneedstwoimplementationclasses:oneclassfortheclientsidewhichis
responsiblefortheactualpaintingandanotheronefortheserversidewhichisresponsiblefor
creatingtheclientbackgroundclassandreadingtheparametersfromtheCSSdefinitions.
Asanexamplewecreateandintegrateananimatedbackground,whichpaintsapulsatingcircle.
PleasenotethatthisbackgroundisnowdirectlyavailableinJ2MEPolishfromversion1.0onwards.

CreatingtheClientSideBackgroundClass
Forusinganewbackground,justcreateanewclasswhichextendsthe
de.enough.polish.ui.Backgroundclass.
Wearestartingwithasimplebackground,whichpaintsafilledoutcircle.Fortheconstructorwe

164
ExtendingJ2MEPolish

onlyneedoneparameterthedesiredcolorofthecircle:
//#condition polish.usePolishGui

package com.company.backgrounds;

import javax.microedition.lcdui.Graphics;
import de.enough.polish.ui.Background;

public class PulsatingCircleBackground extends Background {

private final int color;

public PulsatingCircleBackground( int color ) {


super();
this.color = color;
}

public void paint(int x, int y, int width, int height, Graphics g) {


g.setColor( this.color );
g.fillArc( x, y, width, height, 0, 360 );
}

Thepaintmethodisusedtorenderthebackgroundandneedstobeimplementedbyallsubclasses
ofBackground.The#conditiondirectiveatthetopensuresthatthePulsatingCircleBackgroundis
includedonlywhentheGUIofJ2MEPolishisactuallyused.
Thisbackgroundisuseful,butabitboring,soweaddananimationtoit:thebackgrounddiameter
shouldgrowandshrinkconstantly.Fordoingthisweneedtooverridetheanimate()method,which
isusedtoimplementanimations.Whenthismethodreturnstrue,arepaintwillbetriggered
resultinginacallofthepaint()method.Withreturningfalsethebackgroundindicatesthatno
repaintisnecessary.
public class PulsatingCircleBackground extends Background {

private final int color;


private final int maxDiameter;
private final int minDiameter;
private int currentDiameter;
private boolean isGrowing = true;

public PulsatingCircleBackground( int color, int minDiameter, int maxDiameter ) {


super();
this.color = color;
this.minDiameter = minDiameter;
this.maxDiameter = maxDiameter;
this.currentDiameter = minDiameter;
}

public void paint(int x, int y, int width, int height, Graphics g) {


g.setColor( this.color );
int centerX = x + width / 2;
int centerY = y + height / 2;
int offset = this.currentDiameter / 2;
x = centerX - offset;
y = centerY - offset;
g.fillArc( x, y, this.currentDiameter, this.currentDiameter, 0, 360 );
}

public boolean animate() {

165
ExtendingJ2MEPolish

if (this.isGrowing) {
this.currentDiameter++;
if (this.currentDiameter == this.maxDiameter) {
this.isGrowing = false;
}
} else {
this.currentDiameter--;
if (this.currentDiameter == this.minDiameter) {
this.isGrowing = true;
}
}
return true;
}
}

TheimplementationusesthefieldcurrentDiameter,whichiseitherdecreasedorincreasedineach
runoftheanimate()method.Theconstructornowhastwoadditionalparameters:theminimum
diameterandthemaximumdiameterforthecircle.

CreatingtheServerSideBackgroundClass
ForconvertingCSSstyleinformationintotheappropriatebackgroundobject,weneedtoimplement
aconverterclasswhichextendsde.enough.polish.preprocess.BackgroundConverter.
ThisclassreadstheprovidedCSSinformationandcreatesthesourcecodeforcreatinganew
instance:
//#condition false

package com.company.backgrounds;

import java.util.HashMap;
import org.apache.tools.ant.BuildException;
import de.enough.polish.preprocess.BackgroundConverter;
import de.enough.polish.preprocess.Style;
import de.enough.polish.preprocess.StyleSheet;

public class PulsatingCircleBackgroundConverter extends BackgroundConverter {

public PulsatingCircleBackgroundConverter() {
super();
}

protected String createNewStatement(


HashMap background,
Style style,
StyleSheet styleSheet )
throws BuildException {
String minDiameterStr = (String) background.get( "min-diameter");
if (minDiameterStr == null) {
throw new BuildException("Invalid CSS: the pulsating-circle
background needs the attribute [min-diameter].");
}
String maxDiameterStr = (String) background.get( "max-diameter");
if (maxDiameterStr == null) {
throw new BuildException("Invalid CSS: the pulsating-circle
background needs the attribute [max-diameter].");
}
// now check if these diameters have valid values:
int minDiameter = parseInt("min-diameter", minDiameterStr);
int maxDiameter = parseInt("max-diameter", maxDiameterStr);
if (maxDiameter <= minDiameter ) {

166
ExtendingJ2MEPolish

throw new BuildException("Invalid CSS: the [min-diameter] attribute


of the pulsating-circle background needs to be smaller than the [max-diameter].");
}
if (minDiameter < 0 ) {
throw new BuildException("Invalid CSS: the [min-diameter] attribute
of the pulsating-circle background needs to be greater or equals 0.");
}
// okay, the min- and max-diameter parameters are okay:
return "new com.company.backgrounds.PulsatingCircleBackground( "
+ this.color + ", " + minDiameterStr + ", " + maxDiameterStr + ")";
}

InthemethodcreateNewStatementwereadtheprovidedvaluesfromtheHashMap.Toparse
thesevalueswecanthehelpermethodparseInt( String attributeName, String
attributeValue ), parseFloat( String attributeName, String attributeValue ),
parseColor( String colorValue ) andgetUrl( String url ).

Inourexamplewewanttousetheattributecolor,mindiameterandmaxdiameter.Thecolor
valueisparsedbythesuperclassalreadyandcanbeaccessedwiththis.color.Incasenocolor
hasbeendefined,thebackgroundcolordefaultstowhite.Whenarequiredvalueismissingora
valueissetwrong,wethrowaBuildExceptionexplainingthedetailsofwhatwentwrong.When
everythingisokay,wereturnaStringinwhichanewinstanceofourbackgroundiscreated.
Weincludedthe#conditionfalse,sothatthisfileisneverincludedintheJ2MEapplication.This
isusefulwhenthesamesourcefolderisusedfortheclientbackgroundclassaswellastheserver
backgroundclass.

IntegratingtheCustomBackground
Touseourbackground,weneedtoensurethattheclassescanbefoundandtouseitinthe
polish.cssfile:
Atfirstwemakesure,thattheclasspathincludesourbackgroundproject.Theeasiestwayistodo
thisinthedefinitionoftheJ2MEPolishtaskwithinthebuild.xml:
<taskdef
name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"
classpath="import/enough-j2mepolish-build.jar:import/jdom.jar:
import/proguard.jar:../background-project/bin/classes"
/>
SecondlyweneedtoinformJ2MEPolishabouttheadditionalsourcefolder.Wedothisby
specifyingthesrcDirattributeofthe<build>elementinthebuild.xml.Severaldirectoriescanbe
specifiedbyseparatingthemwithcolons:
<j2mepolish>
[...]
<build
symbols="ExampleSymbol, AnotherExample"
imageLoadStrategy="background"
fullscreen="menu"
usePolishGui="true"
srcDir="source/src:../background-project/source/src"
>
[...]

167
ExtendingJ2MEPolish

</build>
</j2mepolish>

Thirdlyandlastlyweneedtousethenewbackgroundintheresources/polish.cssfileofour
application.AsthetypeweneedtodefinetheSERVERsideconvertingclass:
focused {
padding: 5;
background {
type: com.company.backgrounds.PulsatingCircleBackgroundConverter;
color: white;
min-diameter: 20;
max-diameter: 70;
}
font {
style: bold;
color: fontColor;
size: small;
}
layout: expand | center;
}
Nowwecanbuildtheapplicationby
callingAnttochecktheresult:

AddingaCustomBorder
Addingacustomborderrequiresthesamestepsasforcreatingacustombackground.Insteadof
extendingtheBackgroundclass,weneedtoextendthede.enough.polish.ui.Borderclass.Forthe
serversidethede.enough.polish.preprocess.BorderConverterneedstobeextended.
Pleasenotethatborderscurrentlydonotsupporttheanimate()method,soifyouwanttouse
animatedborders,youneedtoimplementthemwithaBackgroundclass.
Forthisexamplewecreateaprojectcalledborderprojectandaddthefilesenoughj2mepolish
build.jar,enoughj2mepolishclient.jarandthemidp2.jartotheclasspathoftheproject.These
filescanbefoundintheimportfolderoftheJ2MEPolishinstallationdirectory.Pleasenotethat
thisborderisnowdirectlyavailableinJ2MEPolishfromversion1.0onwards.

CreatingtheClientSideBorderClass
Wecreateaborderwhichshoulddrawaroundborderarounditems.Thecolor,widthandstroke
styleofthebordershouldbecustomizable:
//#condition polish.usePolishGui

package com.company.borders;

168
ExtendingJ2MEPolish

import javax.microedition.lcdui.Graphics;
import de.enough.polish.ui.Border;

public class CircleBorder extends Border {

private final int strokeStyle;


private final int color;
private final int borderWidth;

public CircleBorder( int color, int width, int strokeStyle ) {


super();
this.color = color;
this.borderWidth = width;
this.strokeStyle = strokeStyle;
}

public void paint(int x, int y, int width, int height, Graphics g) {


g.setColor( this.color );
boolean setStrokeStyle = (this.strokeStyle != Graphics.SOLID );
if (setStrokeStyle) {
g.setStrokeStyle( this.strokeStyle );
}
g.drawArc( x, y, width, height, 0, 360 );
if (this.borderWidth > 1) {
int bw = this.borderWidth;
while (bw > 0) {
g.drawArc( x + bw, y + bw, width - 2*bw, height - 2*bw, 0, 360
);
bw--;
}
}
if (setStrokeStyle) {
g.setStrokeStyle( Graphics.SOLID );
}
}

The#conditiondirectiveensuresthatthisclassisonlyusedwhentheGUIofJ2MEPolishis
actuallyused.Inthepaint()methodtheborderisrenderedtothescreen.Whenadifferentstroke
stylethanGraphics.SOLIDisused,wesetthatstyleandresetthestyleintheendofthepaint()
method.ThisisaJ2MEPolishspecificconvention,sincetheGraphics.DOTTEDstrokestyleis
hardlyeverused.

CreatingtheServerSideBorderClass
TheserversideborderclassreadstheCSSattributesfromthepolish.cssfileandcreatesthecode
forinitializinganewborder.Theclassneedstoextendthe
de.enough.polish.preprocess.BorderConverterclass:
//#condition false

package com.company.borders;

import java.util.HashMap;
import org.apache.tools.ant.BuildException;
import de.enough.polish.preprocess.BorderConverter;
import de.enough.polish.preprocess.Style;
import de.enough.polish.preprocess.StyleSheet;

169
ExtendingJ2MEPolish

public class CircleBorderConverter extends BorderConverter {

public CircleBorderConverter() {
super();
}

protected String createNewStatement(


HashMap border,
Style style,
StyleSheet styleSheet )
throws BuildException
{
String strokeStyle = (String) border.get("stroke-style");
String strokeStyleCode;
if (strokeStyle != null) {
if ("dotted".equals(strokeStyle)) {
strokeStyleCode = "javax.microedition.lcdui.Graphics.DOTTED";
} else {
strokeStyleCode = "javax.microedition.lcdui.Graphics.SOLID";
}
} else {
strokeStyleCode = "javax.microedition.lcdui.Graphics.SOLID";
}
return "new de.enough.polish.extensions.CircleBorder( "
+ this.color + ", " + this.width + ", " + strokeStyleCode + ")";
}

TheBorderConverteralreadyparsesthecolorandwidthoftheborder.Thecolordefaultstoblack
andthewidthdefaultsto1.Soweonlyneedtoparsethedesiredstrokestyle.Unlessdottedis
defined,weassumethattheGraphics.SOLIDstrokestyleshouldbeused.
TherearesomehelpermethodsforparsingtheCSSattributes:parseInt( String
attributeName, String attributeValue ), parseFloat( String attributeName, String
attributeValue ), parseColor( String colorValue ) andgetUrl( String url ).

Weincludedthe#conditionfalse,sothatthisfileisneverincludedintheJ2MEapplication.This
isusefulwhenthesamesourcefolderisusedfortheclientbackgroundclassaswellastheserver
backgroundclass.

IntegratingtheCustomBorder
Touseourbackground,weneedtoensurethattheclassescanbefoundandtouseitinthe
polish.cssfile:
Atfirstwemakesure,thattheclasspathincludesourborderproject.Theeasiestwayistodothisin
thedefinitionoftheJ2MEPolishtaskwithinthebuild.xml:
<taskdef
name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"
classpath="import/enough-j2mepolish-build.jar:import/jdom.jar:
import/proguard.jar:../border-project/bin/classes"
/>
SecondlyweneedtoinformJ2MEPolishabouttheadditionalsourcefolder.Wedothisby
specifyingthesrcDirattributeofthe<build>elementinthebuild.xml.Severaldirectoriescanbe
specifiedbyseparatingthemwithcolons:

170
ExtendingJ2MEPolish

<j2mepolish>
[...]
<build
symbols="ExampleSymbol, AnotherExample"
imageLoadStrategy="background"
fullscreen="menu"
usePolishGui="true"
srcDir="source/src:../border-project/source/src"
>
[...]
</build>
</j2mepolish>

Thirdlyandlastlyweneedtousethenewbackgroundintheresources/polish.cssfileofour
application.AsthetypeweneedtodefinetheSERVERsideconvertingclass:
focused {
padding: 5;
background: none;
border {
type:
com.company.borders.CircleBackgroundConverter;
width: 2;
color: fontColor;
stroke-style: dotted;
}
font {
style: bold;
color: fontColor;
size: small;
}
layout: expand | center;
}

NowwecanbuildtheapplicationbycallingAnttochecktheresult:

ContributingYourExtensions
PleaseconsidertocontributeyourextensionstotheJ2MEPolishproject.Inanopensourceworld,
everyonecanparticipatefromtheworkofothers.
Donote,however,thatJ2MEPolishisusedcommerciallyaswell.Pleasegetintouchwith
j2mepolish@enough.detodiscussyourcontribution.
Weneedthecodeandacompletedocumentationofyourextension.Preferablytheextensionis
documentedinEnglish,butGermanisalsoaccepted.ItisrecommendedtousetheJavaDoc
conventionswithinthecodeforthebasicdocumentation.TheJ2MEPolishprojectadherestothe
normalJavastyleconventions.Fordistinguishinglocalfrominstancevariables,pleaseusethe
thisoperatorforaccessinginstancevariables.ThisbehaviorcanbeenforcedinEclipsebysetting
thecompileroptionunqualifiedaccesstoinstancevariables.

171
StandaloneTools

StandaloneTools
J2MEPolishincludesstandalonetoolsfor
specializedtasksinthe
${polish.home}/binfolder.

TheBinaryDataEditor
Usethebinaryeditorforcreatingand
modifyingbinarydatalikeleveldatafiles.It
canalsogeneratetheJava/J2MEcodefor
loadingthatdataforyou.
Pleaseloadthespecificationfile
level.definitionandthedatafile
level1.datafromthebinfolderfor Fig.7:The${polish.home}/binfolderonMacOSX.
gettingaworkingexamplesetuplikeshowninthefollowingfigure.

Fig.8:Thebinaryeditorinaction.
WiththeBinaryEditoryoucaneasilyadjustanykindofstructuredbinaryfileslike
forexampleleveldata.Thestructureofthedataiskeptoutsideofthedatafiles
themselvesandhastheextension.definition.Youcanloaddefinitionfileswith
theOpenDefinitioncommandordragginganddroppingthefileoneitherthe
startscriptortheeditorlikeshowninfollowingfigure.
Ineachdefinitionyouwillhaveseveralentrieswhichcanhavearbitrarynameslike

172
StandaloneTools

playerX,playerYandsoon.Youcanalsodefinethetypeofeachdataentry.Thereare
predefinedtypesavailable,butyoucanalsocombineyourowntypesoutofthebasictypesusing
Edit>AddCustomType.

Type Values Explanation


byte 128..+128 StandardJavabytevalue.
unsigned 0..255 Positive8bitvalue.
byte
short 32,768..+32,767 StandardJavashortvalue(uses2bytes).
unsigned 0..2161(65,535) Positive16bitvalue.
short
int 231..2311 StandardJavaintvalue(uses4bytes).
long 263..2631 StandardJavalongvalue(uses8bytes).
boolean true,false Onebyterepresentingtrue(1)orfalse(0).
ASCII Text AstringconsistingofASCIIcharacterswithamaxlengthof255
String characters.TheASCIIStringuseslength+1bytesinthedata
file.
UTFString Text StandardJavaString.
PNGImage Image APNGimage.Suchimagesshouldusuallybethelastentryina
definitionfile,unlessyougenerateyourowncodeforloadingthe
images.

Eachdataentryalsohasacountvalue,whichdetermineshowoftentheentryisrepeated.Youcan
insertstaticnumbershere,butyoucanalsobeabitmoreflexiblebyusingacalculation.Inthe
calculationyoucanuseanyentrywhichislistedbeforetheaffectedentry.Sofaryoucanonlyuse
simpletermsusingoneoperationonanumberofentries.Inthiswayyoucanforexampledefine
firstanumberofcolumnsandanumberofrowsandthenusecolumns*rowsforcalculatingthe
numberofcellsofatablestructure.Justclickintotherespectivecountfieldtostarttheeditorfor
changingthecountvalueoftheentry.
TheBinaryEditorcanalsogeneratetheJ2MEcodeforloadingdatafileswiththecurrentdefinition
justselectCode>GenerateCode.

TheFontEditor
Thefonteditorisusedtogeneratebitmap(*.bmf)fontsoutofanyTrueType(*.ttf)fonts.Such
bitmapfontscanbeusedbytheJ2MEPolishGUIwiththefont-bitmapCSSattributeordirectly
withthede.enough.polish.util.BitMapFont utiliyclass.

173
StandaloneTools

Fig.9:Thefonteditorinaction.

Sincethefonteditordoesnoyetoptimizethegeneratedfontimages,youmightwanttooptimize
theimagesoutsideoftheeditor:JustselectFile>SavePNGImageAs...andedittheimagein
yourfavoriteimageeditingprogram,e.g.TheGimp.YoumightalsowanttousePNGimage
optimizerlikePNGCrush(http://pmt.sourceforge.net/pngcrush/)orPNGOut
(http://advsys.net/ken/utils.htm#pngout).Whenyou'redone,justreloadthePNGimagebyselecting
File>OpenPNGImage.
YoucanalsofinetuneeveryaspectofthebitmapfontbyopeningitintheBinaryEditor:select
File>OpeninBinaryEditortodoso.

174
NonMIDPPlatforms

NonMIDPPlatforms
J2MEPolishcanbeadjustedtosupportseveralplatformsthatsupportmorethanthenormalMIDP
profile.Thekeyforthissupportisthe${polish.home}/platforms.xmlfile,inclusionofplatform
specific(boot)classpaths,andtheautomaticinvocationofpreprocessors,postcompilers,finalizers
andsoon.
BlackBerryandPalmplatformsaresupportedoutofthebox.

DevelopingforBlackBerryDevices
TheBlackBerryplatformofResearchinMotionisquitepopularforbusinessapplications.Normal
MIDletsaswellasBlackBerryspecificapplicationscanbedevelopedwithJ2MEPolish.

Preparations
FortransformingandsigningtheJARfilestotheBlackBerryproprietaryCODformat,the
BlackBerryJavaDevelopmentEnvironment(JDE)needstobeinstalled.TheJDEcanbe
downloadedfromhttp://www.blackberry.com/developers.OnUnixsystemsitcanbeinstalledusing
Wine.
Inyourbuild.xmlscriptyouthenneedtodefinetheblackberry.homepropertywhichpointstothe
installationfolderoftheJDE:
<property
name="blackberry.home"
location="C:/Program Files/Research In Motion/BlackBerry JDE 4.0.2"
/>

ConvertingJARsintoCODs
WhenyoutargetBlackBerrydevicesliketheBlackBerry/7100tdeviceandhavesetthe
blackberry.homeproperty,J2MEPolishwillautomaticallyinvoketherapccompilerfor
convertingtheJARfileintoaCODfileinthefinalizestepofthebuildprocess.
Rememberthatresourcesshouldbelessthan64kbinsize,otherwisetherapcprocesswillabortthe
processing.Youcanusethejarpackagerforcompressingtheresourcesabitbetterthanthe
internalJ2MEPolishjarmechanism:<packager name="jar" />.

SigningCODFiles
J2MEPolishcanalsoautomatetherequestingofsignaturesduringthebuildprocess.Signaturesare
requiredforaccessingsomeBlackberryspecificsecuritysensitiveAPIsandrequireacertificate.In
ordertogetacertificate,youneedtoregisterwithBlackBerryfirst.InyourAntbuild.xmlscriptyou
thenneedtodefinetheblackberry.certificate.dirproperty:
<property name="blackberry.certificate.dir" location="resources/certificates"/>

Incasethesigtool.cskandsigtool.dbfilesarenotincludedinthesamelocationlikethecertificates,
youalsoneedtodefinetheblackberry.sigtool.dirproperty:
<property name="blackberry.sigtool.dir" location="resources/sigtool"/>

175
NonMIDPPlatforms

Whenyouspecifythepasswordaswell,J2MEPolishusesthisforrequestingthesignatureswithout
manualintervention.ForsuchcasesthepasswordneedstocontainonlyASCIIcharacters,otherwise
J2MEPolishcan'tincludethepasswordautomatically.
<property name="blackberry.certificate.password" value="secret"/>

UsingtheJ2MEPolishGUIonBlackBerryDevices
TheJ2MEPolishGUIcanbeusednormallyonBlackBerrydevicesaswell.Inordertomakemost
oftheSystem,J2MEPolishconvertsyourMIDletintoanativeBlackBerryUiApplication.This
allowsJ2MEPolishtoprocesstrackwheeleventsandsooncorrectly.AlsonativeInputFieldsare
usedforthetextinput.
ThesuccessfulconversionrequiresthatyourMIDletusesapublicconstructor.

DevelopingNativeBlackBerryApplications
YoucanalsodevelopnativeBlackBerryapplicationsbydefiningtheblackberry.mainvariable
thatcontainsthenameoftheclassthatextendsnet.rim.device.api.system.Application.
<variable name="blackberry.main" value="com.company.product.ProductApplication"
/>
PleasenotethatthecurrentlyprovidedBlackBerrylibrarydoesnotcontainallavailableclasses,
comparethefollowingTroubleshootingsection.

Troubleshooting

DeactivateObfuscation
YoushoulddeactivateobfuscationforBlackBerrydevices,sincetherapccompileralreadyremoves
anyunneededfields,classesetc.AlsoyoucangetverificationerrorsontheBlackBerrydevices
whenyouenabletheobfuscation.Youcanskiptheobfuscationfortestbuildsaswellasfor
BlackBerrydeviceswiththisdefinition:
<obfuscator name="ProGuard" unless="test || polish.blackberry" />

Library
J2MEPolishincludesthe${polish.home}/import/blackberry4.0.jarlibrarywhichcontainsthemost
importantpackagesthatareadditionallyavailableonBlackBerrydevices.IfyouuseBlackBerry
specificclassesinyourapplicationyoumightencountercompilerproblems,becausecurrentlynot
allavailableclassesareincludedinthedefaultlibrary.InsuchcasesyoucancopytheJARprovided
bytheJDEfrom${blackberry.home}/lib/net_rim_api.jarto${polish.home}/import/blackberry
4.0.jar.SincethisfilecontainsunresolvedclassdependenciesyouneedtouseaJDK1.4.xandmust
notusea1.5JDK.

176
NonMIDPPlatforms

DevelopingforPalmDevices
PalmhandheldsalsosupportJ2MEapplicationswhentheIBMWebSphereEveryplaceMicro
Environment(WEME)hasbeeninstalled.MIDPapplicationscanbeinstallednormallyovertheair
(OTA)asanyotherapplication.IfyouwanttoinstallapplicationsdirectlyviatheUSBconnection
orifyouwanttousethecompletescreensize,theJARfilehastobeconvertedintotheproprietary
PRCformat.

Preparations
ThePalmconverterandsimulatorcanbedownloadedfromhttp://www.palmos.com/dev/tech/java.
WhenyouextracttheWEMEtoolsyouwillfindadditionallibrariesintheTools/libfolder.You
needtoadjusttheCLASSPATHenvironmentvariableofyoursystemtoincludethoselibrariesor
youneedtocopythemto${java.home}/lib.
Inyourbuild.xmlscriptyouthenneedtodefinethepalm.weme.homepropertythatpointstothe
folderintowhichyouhaveextractedtheWEMEtools:
<property
name="palm.weme.home"
location="C:/Program Files/Palm/WEME57"
/>

ConvertingJARsintoPRCs
J2MEPolishautomaticallyconvertsJARfilesintothePalmPRCformatwhenyoutargetPalm
devices.YoucanfinetunetheconversionprocessbyaddingfollowingAntpropertiesorJ2ME
Polishvariablestothebuild.xmlscript:
Name Default Explanation
palm.vendorId A4characterlongvendorID.WhennoIDisdefined,anIDwill
becreatedautomatically.
palm.smallIcon URLofthefilethatcontainsasmallapplicationicon.
palm.largeIcon URLofthefilethatcontainsalargeapplicationicon.
palm.splash URLofthefilethatcontainsasplashimage.
palm.enableHighRes true Enablethehighresolutionmode,sothatyourapplicationcan
usethecompleteavailablescreen.
palm.enableDebug false EnablesthedebugmodeofthePalm.Inthismodeall
System.out.println()messagearestoredonthememorycard.
palm.enableInstall false AutomaticallyinstallsthegeneratedPRCfileontheconnected
Palmhandheld.

ThefollowingexampleaddsasplashimagetotheapplicationanddefinesavendorID:
<variable name="palm.largeIcon" value="resources/native/splash.jpg" />
<variable name="palm.vendorId" value="ENSW" />

177
NonMIDPPlatforms

WhenyoutargetonlyagenericdeviceliketheGeneric/multione,youcaninvoketheconverterby
addingthejar2prcfinalizertothe<build>sectionofyourbuild.xmlscript:
<finalizer name="jar2prc" />

StartingthePalmSimulator
AswithmanyothervendorsyoucanstartthePalmsimulatorbyusingthe<emulator>section.You
needtodefinetheAntpropertypalm.simulator.homethatpointstothefolderthatcontainsthe
PalmSim.exeexecutable:
<property
name="palm.simulator.home"
location="C:/Program Files/Palm/Simulator"
/>

DevelopingDoJaApplicationswithJ2MEPolish
DoJaistheJapaneseJ2MEstandardcreatedbyNTTDoCoMothatalsousesCLDCasits
foundation.ThisstandardprovidessimilarcapabilitiesastheMIDPplatform.J2MEPolishincludes
aDoJasampleapplicationin${polish.home}/samples/doja.

Preparations
YoucandownloadDoJaemulatorsfromtheDoJaDeveloperNetworkathttp://www.doja
developer.net.TherearecurrentlytwoversionsofDoJafortheinternationalmarket:1.5and2.5.
J2MEPolishalreadyincludeslibrariesforbothversions.InJapanDoJa4.0isthecurrentstandard.
InyourIDEyouneedtoincludeeither${polish.home}/import/doja1.5.jaror
${polish.home}/import/doja2.5.jartotheclasspathofyourproject.

J2MEPolishSetup
Inyourbuild.xmlscriptyoumightneedtospecifythedoja.homeAntpropertyincaseyouhavenot
installedtheDoJaSDKtoeitherC:\jDKDoJa2.5orC:\iDK.
Youthenneedtoadjustyourdevicerequirements,sothatyourapplicationisbuildforDoJadevices.
J2MEPolishincludessomevirtualdevicesliketheDoJa/os15orDoJa/os25ones:
<deviceRequirements>
<requirement name="Identifier" value="DoJa/os25" />
</deviceRequirements>

LastbutnotleastyouneedtospecifyyourIApplicationclasswiththe<iappli>elementinside
ofthe<build>element:
<build>
<iappli class="tetris.Tetris" />
<obfuscator name="ProGuard" />
<!-- ... -->
</build>

Youcannowbuildyourapplicationandlaunchtheemulator,e.g.bycallingant emulatorfromthe
commandline.J2MEPolishcreatestheJARfilewithoutaManifestandaJAMinsteadofaJAD
descriptor.

178
NonMIDPPlatforms

OptionalJAMAttributes
SeveralJAMattributesareoptional,soyoucansetthembyspecifyingAntpropertiesorJ2ME
Polishvariablesinyourbuild.xmlscript.Inthefollowingexampleascratchpadsizeof5,120bytes
(=5KB)isreserved:
<variables>
<variable name="doja.SPsize" value="5120" />
</variables>

Thefollowingtableliststheavailableoptionalattributes.
Name Explanation
doja.AppParam Anystartupparameters.Thesecanberetrievedusing
com.nttdocomo.ui.IApplication.getArgs().Multipleparameters
shouldbeseparatedbyaspace.
doja.ConfigurationVer TheJ2MEconfigurationversion,e.g.CLDC-1.0
doja.ProfileVer TheimodeJavaApplicationruntimeenvironmentprofileversion.e.g.
DoJa-1.5oe
doja.SPsize ThesizeoftheScratchPadinbytes.
doja.UseNetwork Settohttpforapplicationswhichusenetworkfunctionality.
doja.TargetDevice Settoamodelnameiftheapplicationistargetedtoaparticular
model.Examplesetting:X430i,Y430i
Donotsetthiskeyforapplicationstargetedtoallmodels.
doja.LaunchAt TolaunchtheimodeJavaApplicationautomaticallyataspecified
time,setthetimehere.
doja.AppTrace Whenthevalueissettoon,anyinformationoutputwith
System.out.println()orSystem.err.println()willbe
displayedaftertheiAppliisterminated.
doja.DrawArea ThesizeoftheimodeJavaApplicationdrawingarea,e.g.120x130
doja.GetUtn DeclaresthattheimodeJavaApplicationreferstothehandset
identificationcodeandICchipinformationonitsSIMorUIMcard.
Examplesetting:terminalid,userid
Thisinformationcanberetrievedusingthe
com.nttdocomo.util.Phone.getProperty()method.

DevelopingDoJaApplicationsunderLinuxandMacOSX
YoucanbuildDoJaapplicationswithoutrestrictionsunderLinuxandMacOSXwithJ2MEPolish.
TheDoJaEmulator/SDKisonlyneededforstartingtheemulator.
TheeasiestwayistoinstalltheDoJaemulatorunderWindowsandthencopythecompletefolder
intoyourUnixfilesystem,sincetheinstallerwon'tworktogetherwithwine.J2MEPolishwilluse

179
NonMIDPPlatforms

winethenautomaticallyforexecutingtheemulatorunderUnixsystems.Remembertospecifythe
doja.homeAntpropertyinyourbuild.xmlscript.

DevelopingforMIDPandDoJaattheSameTime
SincebothMIDPandDoJausetheConnectedLimitedDeviceConfigurationastheirfoundation,
youcansharesomecodebetweenyourDoJaandyourMIDPreleaseofyourapplication.Youcan
usethepolish.midpandpolish.dojapreprocessingsymbolsfordistinguishingbetweenyour
releases.YoucanexcludeasourcefilefortheDoJareleasebyspecifyingthatitrequiresanMIDP
device,forexample.Justusetheappropriate#conditionpreprocessingdirectiveinyourJava
sourcefile:
//#condition polish.midp

Ofcourseyoucanalsousethesesymbolsin#ifdirectivestobranchwithinanutilityclassfor
example:
//#if polish.midp
// store the data in a record store:
RecordStore store = RecordStore.openRecordStore( "name", true );
// ...
//#elif polish.doja
// store data in the scratch pad:
Connection con = Connector.open("scratchpad:///0; pos=0", Connector.WRITE );
// ...
//#endif

Rememberthatyouneedtodothisforyourimportstatementsaswell.

180
CookingTipsandHowTos

CookingTipsandHowTos
BuildingHowTos

HowtoUseSeveralSourceFolders
Youcanuseseveralsourcefoldersbydefiningthesourceattributeofthe<build>elementinthe
build.xmlfile.Justseparatethefolderswithcolonsorsemicolons:
<build
fullscreen="menu"
usePolishGui="true"
sourceDir="source/src:../extensions/source/src"
>

Intheaboveexamplethesource/srcfolderofthecurrentprojectandthesource/srcfolderofthe
extensionsprojectareincluded.ThenotationisOSindependentbytheway.Soyoucanseparate
differentsourcepathswitheitheracolon':'orasemicolon';'andyoucanseparatefolderswitha
slash'/'orabackslash'\'.
Youcanalsousethenested<sources>elementforincludingsourcedirectoriesbasedonconditions.
Inthisexamplethedirectorysource/testisonlyincludedwhentheAntpropertytestistrue:
<build
fullscreen="menu"
usePolishGui="true"
>
<sources>
<source dir="source/src" />
<source dir="source/test" if="test" />
</sources>
...

HowtoIntegrateThirdPartyAPIs

SometimesathirdpartyAPIisneededinaproject.YouhavetodistinguishbetweenAPIswhichare
availableassourcecode,andAPIswhichareavailableinbinaryonlyform.AnothercaseareAPIs
whicharealreadypreinstalledonspecificdevices.DependingonthetypeoftheAPIdifferent
actionsarerequiredforintegratingtheAPI.Pleasedonotforgettoaddthelibrarytotheclasspath
ofyourprojectwithinyourIDE.Thisis,however,outofthescopeofthishowto.

HowtoIntegrateaSourceCodeThirdPartyAPI
WhenathirdpartyAPIisavailableinsourcecode,youcanintegrateitbymodifyingthe
sourceDirattributeofthe<build>elementinthebuild.xmlfile.Considerthecasewhereyour
normalapplicationcodeisplacedinthesource/srcdirectoryandthesourcecodeofthethird
partyAPIinthesource/thirdpartyfolder.YoucannowaddthethirdpartyAPIbysettingthe
sourcDirattributetosource/src:source/thirdparty:
<build
imageLoadStrategy="background"
fullscreen="menu"
usePolishGui="true"
resDir="resources2"

181
CookingTipsandHowTos

sourceDir="source/src:source/thirdparty"
>

ThenotationisOSindependentbytheway.Soyoucanseparatedifferentsourcepathswitheithera
colon':'orasemicolon';'andyoucanseparatefolderswithaslash'/'orabackslash'\'.

HowtoIntegrateaBinaryThirdPartyAPI
WhenathirdpartyAPIisonlyavailableinbinaryform,theycanbeintegratedwiththe
binaryLibrariesattributeofthe<build>elementinthebuild.xmlfile.Thisattributecanpointto
jarorzipfilesortoadirectorycontainingthirdpartylibraries(eitherjarfiles,zipfilesorclass
files).Severallibrariescanbeseparatedbycolons':'orsemicolons';'.Whenthelibrariesare
situatedintheimportfolder,onlythenameofthelibrariesneedtobegiven(insteadofspecifying
thefullpath).
Inthefollowingexamplethebinarylibrarytinylineisintegrated.Thecorrespondinglibraryfile
tinylinegzip.zipissituatedintheimportfolder:
<build
imageLoadStrategy="background"
fullscreen="menu"
usePolishGui="true"
resDir="resources2"
binaryLibraries="tinylinegzip.zip"
>
Inthisexamplealllibrarieswhicharesituatedinthethirdpartyfolderareintegrated:
<build
imageLoadStrategy="background"
fullscreen="menu"
usePolishGui="true"
resDir="resources2"
binaryLibraries="thirdparty"
>

ThenotationisOSindependentbytheway.Soyoucanseparatedifferentsourcepathswitheithera
colon':'orasemicolon';'andyoucanseparatefolderswithaslash'/'orabackslash'\'.

HowtoIntegrateaDeviceAPI
ManydevicesprovideadditionalAPIs,whicharepreinstalledonthedevices.Apopularexampleis
Nokia'sUIAPIwhichprovidesadditionalgraphicandsoundfunctions.Whenadevicesupportsa
specificAPI,thisisnotedwiththeJavaPackagecapabilityofthatdeviceinthedevices.xmlfile
(thisfileisvisibleonlywhenyouhavechosentoinstalltheexternaldevicedatabaseduringthe
installationofJ2MEPolish).
AssumingthatyouwanttouseAPIphonebook,thecorrespondinglibraryfilephonebook.jaror
phonebook.zipjustneedstobecopiedintotheimportfolder(intheJ2MEPolishinstallation
directoryorinyourprojectrootdirectory).Itwillthenbeusedautomaticallyforthedeviceswhich
supportthephonebookAPI.
Youcanmodifytheapis.xmlfile(thisisagainonlyvisiblewhenyouhavechosentoinstallthe
externaldevicedatabase)forspecifyingdifferentlibrarynames,pathsoraliases.Thisisdescribed

182
CookingTipsandHowTos

inmoredetailonpage25.

HowtoUseSeveralObfuscatorsCombined
Youcancombineseveralobfuscatorsjustbyaddingseveral<obfuscator>elementstoyour
build.xmlfile.PleasenotethatcombiningRetroGuardandProGuardactuallyresultsinbigger
classesthanwhenProGuardisusedalone.Findmoreinformationaboutthe<obfuscator>element
onpage48.Findmoreinformationaboutintegratingotherobfuscatorsonpage157.

HowtoMinimizetheMemoryFootprint
ThereareseveralpossibilitiesforminimizingthememoryfootprintofJ2MEPolish:

polish.skipArgumentCheckandpolish.debugVerbose
Definethepreprocessingsymbol"polish.skipArgumentCheck",bysettingthesymbolsattribute
ofthe<build>elementinthebuild.xmlfile.Whenthissymbolisdefined,nomethodarguments
willbecheckedbytheJ2MEPolishGUI.Thisisusuallyfinewhentheapplicationisstable.You
shouldalsoskipthecheckingofargumentsintheapplicationbytestingthe
"polish.skipArgumentCheck"symbolintheapplicationcode:
public void doSomething( int index ) {
//#ifndef polish.skipArgumentCheck
// check the argument only when the "polish.skipArgumentCheck" is not defined:
if (index < 0 || index > this.maxIndex ) {
//#ifdef polish.debugVerbose
throw new IllegalArgumentException("Invalid index [" + index "].");
//#else
//# throw new IllegalArgumentException();
//#endif
}
//#endif
}

Theaboveexamplealsousesthe"polish.debugVerbose"symbolfordeterminingifameaningful
exceptionshouldbethrown.Bygivingverboseinformationonlyincaseswhenitisrequested,some
memorycanbesaved,too.Youcansetandunsetthe"polish.debugVerbose"symbolbymodifying
theverboseattributeofthe<debug>element.Thisisdescribedinmoredetailonpage54.

ImageLoadStrategy
WhenyouusetheJ2MEPolishGUI,selectthe"foreground"imageloadingstrategyforremoving
theoverheadofloadingimagesinabackgroundthread.TheimageLoadStrategyattributeofthe
<build>elementcaneitherbeforegroundorbackground,comparepage36.

Optimizingthe"polish.css"File
WhenyouusetheJ2MEPolishGUI,youshouldnotusedefaultvaluesinyour
resources/polish.cssfile.FormsandListsdonotuseatablelayoutbydefault,forexample.Inthat
caseyoushouldnotsetthecolumnsattributeto1,sincethisisthedefaultbehavioranyhow.It
isbetternottousethecolumnsattributeatallinthiscase.Moreinformationaboutspecial
attributescanbefoundonpage120.
Anotheroptimizationistodefineoftenusedbackgrounds,fontsandbordersintheappropriate

183
CookingTipsandHowTos

sectionoftheresources/polish.cssfile.Inthatcaseyoucanjustrefertotheinstances:
backgrounds {
myBackground {
type: round-rect;
color: gray;
arc: 15;
border-color: black;
border-width: 2;
}
}
title {
background: myBackground;
/** skipping other attributes **/
}
focused {
background: myBackground;
/** skipping other attributes **/
}

Thisisdescribedinmoredetailonpage111.
Athirdoptimizationisnottousedynamicstyles.Thisrequirestheusageofthe#styledirectivein
theapplicationcode.Findmoreinformationaboutstaticanddynamicstylesonpage105.More
informationaboutthe#styledirectivecanbefoundonpage86.
FindmoreinformationabouttheJ2MEPolishGUIfrompage102onwards.

UsingOptimalResources
UsetheresourceassemblingofJ2MEPolishforusingonlythoseresourceswhichareactually
requiredbytheapplication.ForexampleitdoesnotmakesensetoaddMIDIsoundfilesfordevices
whichdonotsupportsuchfiles.Betterputthemintotheresources/midifolder.
Itisalsonotgoodtousehighcolorimagesforhandsetswhichdonotsupportsuchimages.Better
createoptimizedversionsofsuchimages.Thissavesmemoryandhastheadditionalbonusthatyou
donotneedtodependontheditheringofthedevice,whichoftenresultsintoawkwardgraphics.So
put4096colorsimagesintotheresources/BitsPerImage.12folderand65kcolorsimagesintothe
resources/BitsPerImage.16+folder.
Theassemblingofresourcesisdescribedinmoredetailsonpage67.WhenyouusetheJ2ME
PolishGUIyoucanalsousedeviceoptimizeddesigns.Thisisdescribedonpage103.

UsePreprocessing
Withpreprocessingyoucanmakeamazingadjustmentstospecificdeviceswithoutwastingmemory
andwithoutlosingtheportabilityofanapplication.
ConsiderforexamplethisSplashScreensolution,whichshowsastartuplogo.Thisscreenshould
bederivedfromNokia'sFullScreenCanvaswhenthisclassisavailable.Inaclassicsolutionyou
wouldneedtotestifNokia'sAPIisavailableandtoloadaNokiaspecificversionofthe
SplashScreenclass:
public class MyMidlet extends MIDlet {
[...]
public void showSplashScreen() {
Displayable splashScreen;

184
CookingTipsandHowTos

try {
// check if this is a Nokia-device:
splashScreen = Class.forName(MyNokiaSplashScreen).newInstance();
} catch (Exception e) {
// no Nokia API is available, load the classic splash screen:
splashScreen = new MySplashScreen();
}
this.display.set( screen );
}
}

public class MySplashScreen extends Canvas {


public void paint( Graphics g) {
[...]
}
}

public class MyNokiaSplashScreen extends com.nokia.mid.ui.FullCanvas {


public void paint( Graphics g) {
[...]
}
}

WiththepreprocessingcapabilitiesandtheintegrateddevicedatabaseofJ2MEPolishthereisan
easierandmuchmorememoryefficientsolutionavailable:
public class MySplashScreen
//#if polish.api.nokia-ui
extends com.nokia.mid.ui.FullCanvas
//#else
//# extends Canvas
//#endif
{
public void paint( Graphics g) {
[...]
}
}

Anotherexampleistheplaybackofsound.Inaclassicalenvironmentyouwouldneedtocheckthe
supportedformatsatruntimeandthendecidewhichoneshouldbeused.Usingpreprocessingand
thedevicedatabasethisismucheasierandnochecksduringtheruntimearenecessary:
public void playMusic() {
Player player;
//#if polish.audio.mpeg
player = Manager.createPlayer( Class.getResourceAsStream(title.mp3),
audio/mpeg );
player.start();
//#elif polish.audio.amr
player = Manager.createPlayer( Class.getResourceAsStream(title.amr),
audio/amr );
player.start();
//#elif polish.audio.wav
player = Manager.createPlayer( Class.getResourceAsStream(title.wav),
audio/wav );
player.start();
//#elif polish.audio.midi
player = Manager.createPlayer( Class.getResourceAsStream(title.midi),
audio/midi );
player.start();
//#else
//# return;

185
CookingTipsandHowTos

//#endif
}

Withthehelpofpreprocessingyoucanshifttheruntimecheckstothecompilephase.

RemoveDebugCode
Whentheapplicationshouldbeshippedanydebugcodeshouldberemovedfromtheproject.The
easiestwayistousethe#debugand#mdebugpreprocessingdirectives.Thedebuggingcanthenbe
controlledwiththe<debug>elementinthebuild.xmlfile.Thisisdescribedinmoredetailinthe
introductiontoJ2MEPolishonpage14.

GeneralOptimizationTips
Someotherusefultipsforminimizingthememoryfootprintofanapplicationarealsoavailable:
DonotusepureObjectOrientatedProgramming.OOPisgreat,butithassomedrawbacks,notably
theruntimeandmemoryimplications.Trytominimizetheusageofclassesandinterfaces.Tryto
usepreprocessingwheneveritmakessense.Checkifyoureallyneedmethodsforaccessing
variables.Sometimesitisbetterisbettertodeclarethemprotectedorevenpublicandtoaccess
themdirectly.
Ifyouhavetextwhichisdisplayedonlyseldom,considertomovethemintoapropertiesfile.

HowtoSignMIDletswithJ2MEPolish

SigningMIDletscanbeautomatedusingthe<java>subelementofthe<build>element.
KeyscanbegeneratedusingtheJavakeytool,e.g.:
> keytool -genkey -alias SignMIDlet -keystore midlets.ks -keyalg RSA

Fortestingpurposesnocertificateneedstobepurchasedandimported.SuchMIDletscannotbe
installedonrealdevices,however.
Whenanappropriatecertificatewaspurchasedandimportedintothekeystorenamedmidlets.ks
withthekeySignMIDlet,thefollowingtwo<java>elementsneedtobeaddedtothe<build>
element:
<java jar="${wtk.home}/bin/JadTool.jar"
fork="true"
failonerror="true"
if="polish.midp2"
unless="test"
message="Adding signature for device ${polish.identifier}"
>
<arg line="-addjarsig"/>
<arg line="-keypass ${password}"/>
<arg line="-alias SignMIDlet"/>
<arg line="-keystore midlets.ks"/>
<arg line="-inputjad dist/${polish.jadName}"/>
<arg line="-outputjad dist/${polish.jadName}"/>
<arg line="-jarfile dist/${polish.jarName}"/>
</java>
<java jar="${wtk.home}/bin/JadTool.jar"
fork="true"
failonerror="true"

186
CookingTipsandHowTos

if="polish.midp2"
unless="test"
message="Adding certificate for device ${polish.identifier}"
>
<arg line="-addcert"/>
<arg line="-alias SignMIDlet"/>
<arg line="-keystore midlets.ks"/>
<arg line="-inputjad dist/${polish.jadName}"/>
<arg line="-outputjad dist/${polish.jadName}"/>
</java>

Intheaboveexamplethesigningisskippedwhenthetestmodeisactiveorwhenthecurrentdevice
doesnotsupporttheMIDP/2.0standard.Itisassumedthatthemidlets.kskeystoreissituatedin
thesamedirectoryasthebuild.xmlfile.
Pleasenotethatthepasswordneedstobespecifiedasaproperty.Thiscanbedonewithinthe
build.xmlfileoralternatively(forthemoresecurityconsciousfolks)onthecommandlinewith
theDpassword=[value]option:
> ant -Dpassword=secret

InMacOSXWirelessToolkittheJadTool.jarisnotavailable.Itcanbeinstalledtogetherwith
J2MEPolish.InthatcasethepathtotheJadToolneedstobechangedto
${polish.home}/bin/JadTool.jarintheaboveexample.

GUIHowTos

HowtoUseTables
AtablecanbeusedforanyanyForm,ListorChoiceGroup.Thetableisactivatedbysettingthe
columnsattributeandoptionallythecolumnswidthattributeintheresources/polish.cssfile:
form {
padding: 5;
background-color: yellow;
columns: 2;
columns-width: 40, 100;
}

IntheaboveexamplethedynamicstyleformisusedfordesigningallFormscreens.Form
elementswillbeaddedfromlefttorightandfromtoptobottomofthetable.Theleftcolumnwill
be40pixelswide,whereastherightcolumnwilluse100pixels.
FindmoreinformationinthechapterSpecificDesignAttributesonpage120.

HowtoApplytheJ2MEPolishGUIforExistingApplications

Ifanexistingapplicationshouldbepolishedupyoushouldinsert#stylepreprocessingdirectives
withintheapplicationtoallowafinegraineddesign.
//#style mainScreen
List mainScreen = new List( "Main Menu", List.IMPLICIT );

//#style mainScreenItem
mainScreen.append( "Start Game", null );

187
CookingTipsandHowTos

Youthenneedtousestaticstylesinthepolish.cssfile.Staticstylescanhavealmostany
alphanumericalnameandneedtostartwithadot:
.mainScreen {
padding: 5;
background-color: yellow;
columns: 2;
columns-width: 40, 100;
}

Inthelaststepyoushouldrefineyourdesignsbyadjustingthemfordifferenthandsets.Ifyouwant
tomakeadjustmentsfortheSonyEricssonP900forexample,youneedtocreatethefile
resources/SonyEricsson/P900/polish.css.Inthisfileyoucanchangeanysettingswhichyouhave
doneinthebasicresources/polish.cssfile.Rememberthatyouonlyneedtospecifyattributes
whicharedifferent,thismakessubsequentchangeseasier.
Findmoreinformationondesigningforspecificdevicesonpage103.

HowtoApplyDifferentDesignstoOneApplication
Youcanaltertheappearanceofanapplicationeasilybyusingdifferentresourceslikeimages,sound
filesanddesigndefinitions.Youcanuseoneapplicationsourcecodeforcreatingseveraldifferent
applicationswiththistechnique.Thedirattributeofthe<resources>elementinthebuild.xml
filedefaultstotheresourcesfolder,butyoucanchangethistoanyotherfolder.Alternativelyyou
canalsosettheresDirattributeofthe<build>element,whenno<resources>elementisused.
BestpracticeistocreateoneAnt<target>foreachendapplicationinthebuild.xmlfile.Ineach
targetthe<j2mepolish>taskiscopiedandchangesaremadetothedirattributeofthe
<resources>elementandtotheworkDirattributesofthe<build>element:
<target name="girlgame" >
<j2mepolish>
<info
jarName="${polish.vendor}-${polish.name}-girl.jar"
[...] />
<deviceRequirements > [...]
<build
resDir="resources/girl"
workDir="build/girl"
[...]
>
<resources
dir="resources/girl"
/>
[...]
</build>
</j2mepolish>
</target>
<target name="boygame" >
<j2mepolish>
<info
jarName="${polish.vendor}-${polish.name}-boy.jar"
[...] />
<deviceRequirements > [...]
<build
workDir="build/boy"
[...]
>

188
CookingTipsandHowTos

<resources
dir="resources/boy"
/>
[...]
<variable name="player-width" value="12" >
<variable name="player-height" value="12" >
</build>
</j2mepolish>
</target>

Youcanevendefineoralter<variables>tomakefurtheradjustmentswiththehelpof
preprocessing.Youcoulddefinespritedimensionsforexampleeachorsomeofthe<j2mepolish>
tasks:
<variable name="player-width" value="12" >
<variable name="player-height" value="12" >

Thesevariablesthencanbeusedwithintheapplicationwiththeuseofpreprocessing:
//#ifdef player-width:defined
//#= int width = ${player-width};
//#else
int width = 10;
//#endif
//#ifdef player-height:defined
//#= int height = ${player-height};
//#else
int height = 10;
//#endif
Sprite player = new Sprite( playerImage, width, height );

Findmoreinformationonthe<build>elementonpage36.Formoreinformationabout
preprocessing,pleaserefertopage78.

HowtoChangetheLabelsofStandardCommandsandMenuLabels
Thelabelsofthestandardmenucommandscanbechangedbysettingvariableseitherinthe
build.xml fileorwithinthelocalizationmessages.txtfile.

ThisexamplechangestheCancelcommandtoAbbruch(Germanforcancel):
<variables>
<variable name="polish.command.cancel" value="Abbruch"/>
</variables>

Pleaserefertothelocalizationinformationonpage76formoreinformation.

HowtoEnableorDisabletheUsageoftheGUIforaSpecificDevice
J2MEPolish'sGUIisdeactivatedbydefaultforsomeolderdeviceslikethefirstversionofNokia
Series40models.
YoucanoverridethisbehaviorbysettingthesupportsPolishGuiattributeofthedevicein
questioninthedevices.xmlfile,whichislocatedininstallationfolderofJ2MEPolish.When
thefileismissing,reruntheinstallationandchoosetoinstalltheexternaldevicedatabaseas

189
CookingTipsandHowTos

well.
Opendevices.xml andsearchthedeviceinquestion.NowsetthesupportsPolishGuiattribute
:Itneedstobetrue,whenthedeviceshouldsupportJ2MEPolish'sGUI.
<device
supportsPolishGui="false" >
<identifier>Nokia/Series40</identifier>
<!-- and so on -->
</device>

YoucanalsooverridethesettingsinthedevicedatabasebysettingtheusePolishGuiattributeof
the<build>elementinthebuild.xmlfiletoalways.InthatcasetheGUIwillbeusedforall
devices,regardlessofthesettingsinthedevicedatabase.

TroubleShooting

UsingSubfoldersforResources
Subfoldersforresourcesarenotsupportedfortwosimplereasons:
1. TheyareunnecessaryandwastespaceintheapplicationJAR.
2. TheautomaticresourceassemblingofJ2MEPolishisbasedonusingsubfolders.
Findmoreinformationabouttheassemblingofresourcesonpage67.

CompileError
IfyouhaveacompileerrorwithintheJ2MEPolishpackageoracompileerrorwhichseemstobe
erroneous,pleasetryacleanbuild:removethebuildfolderorcalltheantcleanbeforebuilding
again.

PreverifyError
Ifyouhaveapreverifyerror,pleasetryacleanbuild:removethebuildfolderorcalltheant
cleanbeforebuildingagain.

190
Appendix

Appendix
IntroductiontoAnt
ApacheAntisaJavabasedbuildtool.Intheory,itiskindoflikeMake,butwithoutMake's
wrinkles.
J2MEPolishusesAntasitsfoundationforthebuildprocess,thereforeitisusefultogettoknow
AntalittlebittomakethemostoutofJ2MEPolish.
Thefilebuild.xmlisanXMLbaseddocumentwhichcontrolsandconfiguresAnt.Thebasic
syntaxconsistsofthethe<project>rootelementandseveral<target>elements.Each<target>
elementisnormallyusedtoaccomplishoneorseveralspecifictasks:
<project name="enough-polish-example" >

<target name="clean">
<delete dir="build" />
<delete dir="dist" />
</target>

</project>

Intheaboveexamplewehaveonetargetcalledcleandefinedwhichusestwo<delete>tasksfor
whowouldhavethoughtthatdeletingtwofolders.
AssumingthatAnthasbeensetupcorrectly(comparepage21)andthatyouareinthedirectory
containingthebuild.xmlfile,youcancalleachofthedefinedtargetsbycallingant[target
name]onthecommandline.Intheaboveexampleonlyonetargetisavailable,soyoucanonlycall
antclean.
Usuallythereareseveraltargetsdefinedinthebuild.xmlfile.Inthatcaseitususefultodefinea
defaulttarget,whichisexecutedwhenevernotargethasbeenspecified:
<project name="enough-polish-example"
default="hello"
>

<target name="hello">
<echo message="Hello World!" />
</target>

<target name="clean">
<delete dir="build" />
<delete dir="dist" />
</target>

</project>

Nowthehellotargetwillbeexecuted,whenjustantiscalledfromthecommandline.
AnotherpowerfulfeatureofAntareproperties,whicharelikevariableswiththedifferencethatthey
canonlysetonce:afterapropertyisset,itcannotbechangedanymore.Thiscanbecombinedwith
dependenciesoftargetstocreatecomplexbehavior:

191
Appendix

<project name="enough-polish-example"
default="hello"
>
<target name="deploy">
<property name="deploy-url"
value="http://www.company.com/download"/>
</target>

<target name="init">
<property name="deploy-url" value="http://localhost"/>
</target>

<target name="hello" depends="init">


<echo message="The deploy-url is ${deploy-url}" />
</target>

<target name="clean">
<delete dir="build" />
<delete dir="dist" />
</target>

</project>

Intheaboveexamplethepropertydeployurlisdefinedintwotargetseitherininitorin
deploy.Whenwecallanthelloorjustantthepropertywillbehttp://localhost,becausethe
hellotargetdependsontheexecutionoftheinittarget:
> ant
Buildfile: build.xml

init:

hello:
[echo] The deploy-url is http://localhost

BUILD SUCCESSFUL
Total time: 1 second
Butwhenwecallantdeployhellothepropertywillcontainthevalue
http://www.company.com/downloadinstead,sincethedeploytargetwillbecalledfirst,thenthe
inittarget(sincethehellotargetdependsontheinittarget)andlastbutnotleastthe
hellotarget:
> ant deploy hello
Buildfile: build.xml

deploy:

init:

hello:
[echo] The deploy-url is http://www.company.com/download

BUILD SUCCESSFUL
Total time: 1 second

HowtoUseQuotationMarksinAttributes
Sometimesquotationmarksareneededwithinattributevalues.Suchspecialcharactersneedstobe

192
Appendix

specifiedxmlencoded,aquotationmarkisencodedwith&quot;.

HowtoSpecifyPropertiesontheCommandLine
YoucanspecifyAntpropertiesonthecommandlinewiththeD[name]=[value]option,e.g.
> ant -Dpassword=1234

Suchpropertiescanbeuselikeanyotherpropertieswithinthebuild.xmlscript.

ThisclosestheshortintroductiontoAnt.Werecommendeitheroneofthemanygoodbooksabout
AntortoconsulttheofficialAntmanualathttp://ant.apache.org/manual/ forfurther
information.

193
Appendix

Licenses
J2MEPolishislicensedundertheGNUGeneralPublicLicense(GPL)aswellasseveral
commerciallicenses.

GNUGPL
YoucanusetheGPLlicenseforprojects,whicharelicensedundertheGNUGeneralPublicLicense
withoutlimitations.
MoreinformationabouttheGPLisavailableatthesesites:
http://www.gnu.org/licenses/gpl.html
http://www.gnu.org/licenses/gplfaq.html

CommercialLicenses
IfthesourcecodeofyourmobileapplicationsshouldnotbepublishedundertheGNUGPLlicense,
youcanuseoneofthefollowingcommerciallicenses:
SingleLicense
Thesinglelicensecanbeusedforthecreationanddistributionofonemobileapplication.
RuntimeLicense
Theruntimelicensecanbeusedforthecreationofanynumberofmobileapplications.The
drawbackisthatallapplicationstogethercanbeinstalled/soldonlya100hundredtimes.
EnterpriseLicense
Theenterpriselicenseallowstocreateandsellanynumberofapplications.
Thepricingandlicensetermscanbeobtainedathttp://www.j2mepolish.org/licenses.html.

194
Contact

Contact

ENOUGH SOFTWARE
Robert Virkus
Vor dem Steintor 218
28203 Bremen
Germany

Telephone +49 (0)421 98 89 131


Fax +49 (0)421 98 89 132
Mobile +49 (0)160 77 88 203
E-Mail j2mepolish@enough.de
Web www.enough.de

195

Você também pode gostar