Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
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
13
IntroductiontoJ2MEPolish
.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
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:
26
TheDeviceDatabase
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
<!-- 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>
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
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:
31
TheBuildProcess
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
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
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
37
TheBuildProcess
38
TheBuildProcess
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>
39
TheBuildProcess
<midlet>and<midlets>
The<midlet>elementdefinestheactualMIDletclass:
<midlet class="de.enough.polish.example.ExampleMidlet" />
<iappli>
The<iappli>or<doja>elementdefinestheIApplicationclassofyourDoJarelease.Thisisonly
applicablewhenyouaretargetingthisplatform(seepage178).
iappli Require
Explanation
Attribute d
40
TheBuildProcess
<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:
41
TheBuildProcess
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"/>
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
The<localization>Subelement
Withthe<localization>elementtheinternationalizationoftheapplicationcanbecontrolled.It
supportsfollowingattributes:
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
44
TheBuildProcess
<compiler>
Theoptional<compiler>elementcanbeusedforspecifyinganycompilerarguments.J2MEPolish
normallycallstheJavacompilernormallywiththeappropriateclasspathaswellasbootclasspath
forthecurrenttargetdevice.Insomecasesyoumightwanttoadjustthecompilersettings,however,
soyoucanusethenested<compiler>element.Alongtoallattributesofthestandard<javac>task,
the<compiler>elementalsosupportsthe"if"and"unless"attributesforselectingtoappropriate
compilersetting:
45
TheBuildProcess
46
TheBuildProcess
The<compilerargs>Subelement
Youcanspecifyadditionalcommandlineargumentsforthecompilerwithnested<compilerarg>
47
TheBuildProcess
elements.TheseelementsarespecifiedlikeCommandlineArgumentsbuthaveanadditional
attributethatcanbeusedtoenableargumentsonlyifagivencompilerimplementationwillbeused.
<obfuscator>
Theoptional<obfuscator>elementcontrolstheobfuscatingoftheapplicationbundle,which
decreasesthejarsizeandmakesitdifficulttoreverseengineertheapplication.
<obfuscator name="ProGuard" useDefaultPackage="true" unless="test" />
48
TheBuildProcess
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>
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>
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>
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.
54
TheBuildProcess
Forafinercontrolofthedebuggingprocess,the<debug>elementallowsthesubelement<filter>,
whichdefinesthedebuglevelforspecificclassesorpackages.
<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>
1 JavaApplicationDescriptor
55
TheBuildProcess
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:
56
TheBuildProcess
Insideofthe<jadfilter>elementyoucanspecifyallallowedJADattributesinthedesiredorderand
separatedbycommas.Followingsyntaxisused:
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:
57
TheBuildProcess
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>
58
TheBuildProcess
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:
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:
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:
62
TheBuildProcess
The<parameter>Subelement
The<emulator>elementsupportsthenestedsubelement<parameter>fordefiningadditional
commandlineparameters:
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
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
68
ResourceAssembling
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 ),
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
[...]
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;
[...]
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
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
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
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
Inthetermsthebooleanoperators&&,||,^and!canbeused.Complextermscanbeseparated
usingnormalparenthesizes(and).Thetermargumentsforbooleanoperatorsaresymbols,
whicharetruewhentheyaredefinedandfalseotherwise.
Variablescanbecheckedwiththecomparator==,>,<,<=and>=.Argumentsforthecomparators
arevariablesorconstants.
Atermcanincludecomparatorsandbooleanoperators,whenthesectionsareseparatedby
parenthesizes.
80
TheWorldofPreprocessing
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
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
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:
86
TheWorldofPreprocessing
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
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.
95
TheJ2MEPolishGUI
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
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
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;
//#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 );
}
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:
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:
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.
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
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
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
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:
114
TheJ2MEPolishGUI
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:
116
TheJ2MEPolishGUI
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
UsingBitmapFontsDirectly
Thebitmapfontscanalsobeuseddirectlyintheprogramcodewiththehelpofthe
de.enough.polish.util.BitMapFontclass.PleasecomparetheJavaDocdocumentationformore
information.
Thisexampleusesabitmapfontfordisplayingatext:
import de.enough.polish.util.*;
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
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
Currentlyonlyimagescanbeincluded.
SpecificDesignAttributes
ManyGUIitemssupportspecificCSSattributes.
Fig.4:Theafterattributein
Backgrounds action.
TherearemanydifferentbackgroundtypeswhichmakeuseofspecificCSSattributes.When
anotherbackgroundthanthedefaultsimplebackgroundortheimagebackgroundshouldbeused,
thebackgroundtypeattributeneedstobedeclared.
Whennobackgroundatallshouldbeused,thebackground: none;declarationcanbeused.
SimpleBackground
Thesimplebackgroundjustfillsthebackgroundwithonecolor.Whennobackgroundtypeis
specified,thesimplebackgroundisusedbydefault,unlessthebackgroundimageattributeisset.
Inthelatercasetheimagebackgroundwillbeused.
Thesimplebackgroundsupportsthecolorattribute:
Thefollowingstylesuseayellowbackground:
.myStyle {
background-color: yellow;
}
.myOtherStyle {
background-color: rgb( 255, 255, 0 );
}
RoundRectBackground
Theroundrectbackgroundpaintsarectangularbackgroundwithroundedges.Itsupportsfollowing
attributes:
120
TheJ2MEPolishGUI
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:
121
TheJ2MEPolishGUI
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:
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:
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
Thefollowingexampleusestheopeningbackground:
.myStyle {
background {
type: opening;
color: bgColor;
start-height: 2;
steps: 4;
}
}
OpeningRoundRectBackground
Theopeningroundrectanglebackgroundpaintsananimatedbackgroundwhichheightstartssmall
andthenincreaseswheneveritchangestheposition.Itsprimaryuseisforthefocusedstyle.It
supportsfollowingattributes:
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:
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:
BallGamesBackground
Theballgamesbackgroundpaintsananimatedbackgroundwithannumberofspriteswhich
movingthroughthebackground.Itsupportsfollowingattributes:
127
TheJ2MEPolishGUI
}
}
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
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:
130
TheJ2MEPolishGUI
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
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.
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;
}
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:
.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:
Dependingontheappearancemode11ofthetext,eitherthep,theaorthebuttonselectoris
usedfordynamicstyles:
DynamicSelector Explanation
p Thepselectorisusedfornormaltexts.
a Theaselectorisusedforhyperlinks.
11 TheappearancemodecanbesetintheapplicationcodewithItem.setAppearanceMode(int).
137
TheJ2MEPolishGUI
DynamicSelector Explanation
button Thebuttonselectorisusedforbuttons.
Seethegeneralexplanationofdynamicstylesonpage107formoredetails.
TheIconItem
Iconscanonlybeuseddirectly.Iconssupportfollowingadditionalattributes:
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
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
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:
140
TheJ2MEPolishGUI
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
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
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
TheDateField
ADateFieldisusedtoenterdateortimeinformation.Currentlytheinputisdonewiththeuseofthe
nativefunctions,sothatspecialinputmodescanbeused(likeT9orhandwritingrecognition).The
DateFieldsupportsfollowingadditionalattributes:
144
TheJ2MEPolishGUI
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:
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
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 MyPreprocessor() {
super();
registerDirective("date");
}
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:
163
ExtendingJ2MEPolish
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;
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 {
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 PulsatingCircleBackgroundConverter() {
super();
}
166
ExtendingJ2MEPolish
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;
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 CircleBorderConverter() {
super();
}
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.
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 );
}
}
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="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".
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
195