You are on page 1of 68

TheCompleteGuidetoJ2MEPolish TheSolutionfor ProfessionalMIDletProgramming

TableofContents
Introduction........................................................................................................................5 Installation..........................................................................................................................6 Requirements...................................................................................................................6 InstallationofJ2MEPolish...............................................................................................6 UpdatingJ2MEPolish......................................................................................................6 IntegratingJ2MEPolishintoEclipse................................................................................6 TheDeviceDatabase.........................................................................................................8 vendors.xml......................................................................................................................8 groups.xml........................................................................................................................8 devices.xml......................................................................................................................9 Capabilities.....................................................................................................................10 apis.xml..........................................................................................................................11 TheBuildProcess............................................................................................................13 Introduction....................................................................................................................13 DefinitionoftheJ2MEPolishtask.................................................................................13 Example.........................................................................................................................13 TheinfoSection.............................................................................................................15 ThedeviceRequirementsSection..................................................................................17 ThebuildSection...........................................................................................................19
AttributesofthebuildSection.................................................................................................20 ElementsofthebuildSection.................................................................................................21 <midlet>and<midlets>......................................................................................................21 <obfuscator>......................................................................................................................22 <variables>........................................................................................................................23 <debug>.............................................................................................................................23

TheWorldofPreprocessing...........................................................................................26 CheckingaSingleSymbolwith#ifdef,#ifndef,#else,#elifdef,#elifndefand#endif.....26 CheckSeveralSymbolsandVariableswith#if,#else,#elifund#endif.........................27 HidingCode...................................................................................................................29 Debuggingwith#debug,#mdebugand#enddebug......................................................30


DebugLevels..........................................................................................................................30 TheDebugUtilityClass..........................................................................................................31

UsingVariableswith#=.................................................................................................32 SettingCSSStyleswith#style.......................................................................................33 ExcludeorIncludeCompleteFileswith#condition........................................................34 DefiningTemporarySymbolswith#defineand#undefine.............................................34 InsertingCodeFragmentswith#include........................................................................35 UsefulSymbols..............................................................................................................35


APIsandMIDPVersion..........................................................................................................35 J2MEPolishSymbols.............................................................................................................35

UsefulVariables.............................................................................................................35
FileOperations........................................................................................................................36

TheJ2MEPolishGUIforDesigners...............................................................................37 AQuickGlance..............................................................................................................37 DesigningforSpecificDevicesorDeviceGroups.........................................................38


TheHierarchyoftheresourcesFolder.................................................................................38 Groups....................................................................................................................................39 APIandJavaPlatformGroups.........................................................................................39 BitsPerPixelGroups...........................................................................................................39

Dynamic,StaticandPredefinedStyles..........................................................................40
StaticStyles............................................................................................................................40 PredefinedStyles....................................................................................................................41 DynamicStyles.......................................................................................................................41

ExtendingStyles............................................................................................................43 CSSSyntax....................................................................................................................44
StructureofaCSSDeclaration...............................................................................................44 Naming....................................................................................................................................44 GroupingofAttributes.............................................................................................................44 ReferringtoOtherStyles........................................................................................................45 Comments...............................................................................................................................45

CommonDesignAttributes............................................................................................45
Structureofpolish.css.............................................................................................................45 StructureofaStyleDefinition.................................................................................................45 TheCSSBoxModel:MarginsandPaddings.........................................................................46 TheLayoutAttribute................................................................................................................47 Colors......................................................................................................................................49 PredefinedColors..............................................................................................................49 ThecolorsSection.............................................................................................................49 HowtoDefineColors.........................................................................................................49 AlphaBlending...................................................................................................................50 FontsandLabels....................................................................................................................50 BackgroundsandBorders......................................................................................................52 BeforeandAfterAttributes.....................................................................................................52

SpecificDesignAttributes..............................................................................................53
Backgrounds...........................................................................................................................53 SimpleBackground............................................................................................................53 RoundRectBackground....................................................................................................53 ImageBackground.............................................................................................................54 PulsatingBackground........................................................................................................55 Borders....................................................................................................................................55 SimpleBorder....................................................................................................................56 RoundRectBorder............................................................................................................56 ShadowBorder..................................................................................................................57 Screens:List,FormandTextBox...........................................................................................57 PredefinedStylesforLists,FormsandTextBoxes............................................................57 AdditionalAttributesforScreens.......................................................................................58 DynamicStylesforScreens...............................................................................................59

List...................................................................................................................................59 Form.................................................................................................................................59 TextBox...........................................................................................................................59


Example.............................................................................................................................59 TheStringItem:Text,HyperlinkorButton...............................................................................61 TheIconItem...........................................................................................................................62 TheChoiceItem.......................................................................................................................62 TheChoiceGroup....................................................................................................................63 TheGauge..............................................................................................................................64 TheTextField..........................................................................................................................65 TheDateField..........................................................................................................................66

Appendix...........................................................................................................................67 IntroductiontoAnt..........................................................................................................67 Licenses.........................................................................................................................67


GNUGPL................................................................................................................................67 CommercialLicenses..............................................................................................................67

Contact..............................................................................................................................68

Introduction

Introduction
J2MEdevelopersfaceaseriousproblem:eithertheyuseonlythecommondenominatorofJ2ME devicestheMIDP/1.0standardortheychoosetosupportonlyafewhandsets,forwhichthey optimizetheirapplicationswithalotofenergy.TheopensourcetoolJ2ME Polishpromisesa solutiontothisproblemandmore. J2MEPolisheasesthedevelopmentofmobileapplicationssignificantly.Theoptimizationforthe differenthandsetsisdoneautomatically;developerscanmakeuseofthedevicespecific capabilitieswithoutendangeringthecompatibilityoftheapplication.ThankstotheoptionalGUI theapplicationcanbedesignedusingtheWebstandardCSS.WebdesignerscannowdesignJ2ME applicationswiththeirknowhowandwithoutchangingthesourcecodeofanapplication. TheJ2MEPolishframeworkisdividedintotheJ2MEandthebuildsection.IntheJ2MEsection youwillfindsomeutilitieslikeanArrayListaswellasthealreadymentionedGUIAPI,whichis compatibletotheMIDP/1.0andMIDP/2.0standard.Inthebuildsectionallstepsforbuildinga J2MEapplicationaredone:preprocessinganddeviceoptimization,compilation,preverification, creationofjarandjadfilesandobfuscationoftheapplication.ThebuildprocessisbasedonAnt thestandardtoolforbuildingJavaapplications.J2MEPolishthusworkswithallIDEs.Inthebuild areathereisanadditionaldevicedatabase,whichisbasedonXMLandcanbeextendedeasily.The devicedatabaseisthekeytotheautomaticoptimizationoftheapplications. SinceJ2MEPolishiscompatibletotheMIDP/1.0andMIDP/2.0standard,thesourcecodeof existingapplicationsdoesnotneedtobechanged.Evenexistingpreprocessingdirectivescanbe used,sinceJ2MEPolishsupportsalldirectivesoftheantennapreprocessor.Theprogrammeronly needstocreateabuild.xmlfilewhichcontrolsthebuildprocess.Whentheextendedcapabilitiesof theJ2MEPolishGUIshouldbeused,oneshould(butisnotrequiredto)addsomestyledirectives inthecode.Adjustmentstospecificdevicesareeasywiththehelpofthepreprocessingandthe devicedatabase. ObviouslyonecanextendandusethemoreadvancedfeaturesoftheJ2MEPolishframework.You canuseyourownwidgets,addyourownpreprocessor,orintegrateyourownobfuscatorwithease. IhopeyoufindJ2MEPolishusefulandIwishyoualotoffunwithit! Bremen.Germany,June2004 RobertVirkus/EnoughSoftware

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 FavoriteIDE,forexampleEclipse3.0,http://www.eclipse.org Ant1.5orhigher,ifnotalreadyintegratedintheIDE,http://ant.apache.org

InstallationofJ2ME Polish ForinstallingJ2MEPolishdownloadthelatestreleaseandstarttheinstallationeitherbydouble clickingthefileorbycalling"javajarj2mepolish$VERSION.jar"fromthecommandline(where $VERSIONdenotesthecurrentversionofJ2MEPolish).ItisrecommendedtoinstallJ2MEPolish intoaprojectfolderofyourworkspace,e.g."$HOME/workspace/j2mepolish". TheinstallerofJ2MEPolishcontainsasampleMIDletapplicationwithtwodifferentdesigns.This applicationisoptimizedforNokiaSeries60devices,soitisrecommendedtohavesuchanemulator installed.TheNokiaemulatorcanberetrievedfromhttp://forum.nokia.com. Tobuildthesampleapplication,runtheincludedbuild.xmlfromyourfavoriteJavaIDEorcall "ant"fromthecommandline.Call"antnotestj2mepolish"tobuildandobfuscatethesample application. UpdatingJ2MEPolish Whenyouwanttoupdateanexistinginstallation,youdonotneedtoreinstallthewholepackage. Forsavingbandwidthyoucandownloadjusttheupdatepackage.Thispackagejustcontaintsthe twoJARfilesenoughj2mepolishbuild.jarandenoughj2mepolishclient.jarwhichneedtobe copiedintothe"import"folderofyourinstallation. IntegratingJ2MEPolishintoEclipse TointegrateJ2MEPolishintoEclipseitisbesttoinstallJ2MEPolish(withtheincludedsample application)intoanewfolderinyourworkspacecalled"myproject"(oranyothername).Thenstart Eclipseandcreateanewprojectcalled"myproject".Eclipsethenautomaticallyintegratesall sourcefilesandsetstheclasspath. Optionallyyoucanchangethebuildsettingsbymodifyingthefile"build.xml"(whichislocatedin therootofyourproject).ForexampleyoucanchangethedeviceRequirementsifyouwantto.The exampleisoptimizedtoNokiaSeries60devices. YoucannowcreatetheJARandJADfilesbyrightclickingthebuild.xmlfile,selecting"RunAnt" andrunningAntinthenextdialog.YouwillfindtheJARandJADfilestheninthe"dist"folderof theproject.IfyouwanttoaccessthemfromwithinEclipse,youmightneedtorefreshyourproject: Rightclicktheprojectandselect"Refresh". AfteryouhaveinstalledJ2MEPolish,youwillfindfollowingstructureinyourproject(assuming 6

Installation thatyourprojectiscalledmyprojectandyourworkspaceworkspace): Folder/File


workspace/myproject workspace/myproject/build.xml workspace/myproject/devices.xml workspace/myproject/vendors.xml workspace/myproject/groups.xml workspace/myproject/apis.xml workspace/myproject/resources workspace/myproject/resources/polish.css workspace/myproject/import workspace/myproject/build workspace/myproject/dist Theapplicationsproject Thecontrollerofthebuildprocess DefinitionofJ2MEdevices(onlyinstalledwhenyouselectedto installtheexternaldevicedatabase) DefinitionofJ2MEdevicevendors(onlyinstalledwhenyou selectedtoinstalltheexternaldevicedatabase) Definitionofdevicegroups(onlyinstalledwhenyouselectedto installtheexternaldevicedatabase) DefinitionofsomecommonJ2MElibraries(onlyinstalledwhen youselectedtoinstalltheexternaldevicedatabase) Folderforallresourcesanddesigndescriptionsoftheproject Basicdesigndescription NeededAPIs Temporarybuildfolder,willbecreatedautomatically.Shouldnot besharedinCVSandsimilarsystems. Folderforthereadytodeployapplications.Itwillbecreated automatically.ShouldnotbesharedinCVSandsimilarsystems.

Description

Tip:Youdon'tneedthefilesdevices.xml,vendors.xml,groups.xmlandapis.xml,since theyarealsocontainedinthejarfileenoughj2mepolishbuild.jar.Ifyoudon'twanttochange them,youcandeletethem.

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 proprocessing(comparechapterTheworldofpreprocessing,page26).Featuresarejustacomma separatedlist,whereascapabilitiesalwayshaveanameandavalue. 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>

ThegroupNokiaUIisusedfordeviceswhichsupporttheUIAPIofNokia.ThegroupSerie60 extendsthisgroup.Anycapabilitiesorfeaturesdefinedinthegroupscanbeoverriddenor completedbythedevicedefinitions.

TheDeviceDatabase 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,thusyoucannotusethesamenameforaSoftwarePlatformanda HardwarePlatformcapability. Theidentifierconsistsofthevendoranddevicename.Thestructureis[vendor]/[devicename]. The<features>elementdefinespreprocessingsymbols.Thesecanbecheckedinthesourcecode forexamplewith//#ifdef[symbolname].Severalfeaturesneedtobeseparatedbycomma:


<features>supportsPointer, roundKnobs</features>

Groupscanbedefinedexplicitlywiththe<groups>element.Allgroupnamestowhichthedevice belongsareinacommaseparatedlist: <groups>Series60, SomeGroup</groups> defines2groupsforthedevice.Groupscanalsobe definedindirectlybythecapabilitiesofthedevice. The<device>ElementsupportsthesingleattributesupportsPolishGui:


<device supportsPolishGui="true">...

NormallyitiscalculatedwhetheradevicesupportstheJ2MEPolishGUI:whenithasacolordepth ofatleast8bitsperpixelandaheapsizeof500kbormore,thedevicesupportstheGUI.The supportsPolishGuiattributeoverridesanycalculations.

TheDeviceDatabase Capabilities Capabilitiescanbedefinedintwodifferentways:


<capability name="ScreenSize" value="176x208"/>

isequivalentwith

<capability> <capability-name>ScreenSize</capability-name> <capability-value> 176x208</capability-value> </capability>

Youcanusecapabilitieswithanyname,butfollowingcategoriesarepredefined: Capability
BitsPerPixel

Explanation
Colordepth:1ismonochrome, 4are16colors, 8=256colors, 16=65.536colors, 24=16.777.216colors

PreprocessingAccess
Variable: polish.BitsPerPixel, Symbols: polish.BitsPerPixel.1or polish.BitsPerPixel.4, polish.BitsPerPixel.16etc

Groups
At8bitsperpixelfor example: BitsPerPixel.4+ and BitsPerPixel.8

ScreenSize

Widthtimesheightofthescreen Variables: resolutioninpixels,e.g.176x polish.ScreenSize, polish.ScreenWidth, 208 polish.ScreenHeight Symbols(example): polish.ScreenSize.176x208 polish.ScreenWidth.176 polish.ScreenHeight.208

CanvasSize

WidthtimesheightofanMIDP LikeScreenSize Canvas. Variables: polish.CameraResolution, polish.CameraWidth, polish.CameraHeight Symbols(example): polish.CameraResolution.320x 200 polish.CameraWidth.320 polish.CameraHeight.200

CameraResolution Resolutionofthecamera.

JavaPlatform

ThesupportedJavaplatform. CurrentlyeitherMIDP/1.0or MIDP/2.0. SupportedAPIs,e.g.nokiaui, mmapi

Variable:polish.JavaPlatform midp1ormidp2 Symbols: polish.midp1or polish.midp2 Variables: polish.api, polish.JavaPackage Symbols(examples): polish.api.nokiaui polish.api.mmapietc Respectivelythenameof thesupportedAPI,e.g. nokiauiormmapi(one groupforeachsupported API).

JavaPackage

10

TheDeviceDatabase Capability
JavaProtocol

Explanation
Supporteddataexchange protocols.AllMIDP/1.0devices supporttheHTTPprotocol.All MIDP/2.0devicessupport additionallytheHTTPS protocol. Themaximumheapsize,e.g. 500kbor1.2MB Themaximumsizeofthe MIDletJARbundle,e.g.100 kbor2MB Theoperatingsystemofthe device,e.g.SymbianOS6.1

PreprocessingAccess
Variable: polish.JavaProtocol Symbols(example): polish.JavaProtocol.serial polish.JavaProtocol.https Variable: polish.HeapSize Variable: polish.MaxJarSize Variable: polish.OS

Groups

HeapSize MaxJarSize

OS VideoFormat

Thesupportedvideoformatsof Variable: thedevice,e.g.3GPP,MPEG polish.VideoFormat 4 Symbols(examples): polish.VideoFormat.3gpp polish.VideoFormat.mpeg4 Thesoundformatswhichare supportedbythedevice,e.g. midi,wav Variable: polish.SoundFormat Symbols(examples): polish.SoundFormat.midi polish.SoundFormat.wav

SoundFormat

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>

11

TheDeviceDatabase

Intheaboveexampletwolibrariesaredefined.The<name>elementdescribesthedefaultnameofa library,whereasthe<names>elementdefinesotherpossiblenamesofthelibrary.The<files> elementdefinesthenamesofthelibraryonthefilesystem.The<path>elementjustdefinesthe defaultpath.Whenthatpathisnotfound,J2MEPolishtriestofindtheAPIwiththehelpofthefile namesdefinedinthe<files>element.

12

TheBuildProcess

TheBuildProcess
Introduction Thebuildprocesscreatesreadytodeploy,optimizedapplicationbundlesfromthesourcecode. Theprocessiscontrolledbythebuild.xmlfile,whichissituatedattherootoftheproject.Thisfile isastandardAntfilewhichisusedtocontroltheJ2MEPolishtask.Youcanfindashort introductiontoAntintheappendixonpage67.TheJ2MEPolishtaskisseparatedintothesections info,deviceRequirementsandbuild.Duringthebuildfollowingstepsareaccomplished:

Selectionofthesupporteddevices Assemblingoftheresources Preprocessingofthesourcecode,optimizingforthedevice Compilationoftheapplication Obfuscationandshrinkingofthecompiledcode Preverification CreationoftheJARandJADfiles

foreachselected device

DefinitionoftheJ2ME Polishtask YouneedtodefinetheJ2MEPolishtaskinthebuild.xmlfile:


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

Nowyoucanusethe2MEPolishTaskunderthenamej2mepolish. YoucanalsodefinewheretofindoptionalandMIDPAPIs.YoujustneedtodefineanAnt propertywiththenamepolish.api.[apiname]andthelocationoftheAPI:


<property name="polish.api.nokia-ui" location="/home/enough/Nokia/Devices/Series_60_MIDP/lib/ext/nokiaui.zip"/>

WhenyoudonotdefinethelocationofanAPI,itwillbesearchedintheimportfolderunderthe nameoftheAPI:import/[apiname].jarorimport/[apiname].zip.TheNokiaUIAPIwouldbe searchedatworkspace/application/import/nokiaui.jaroratworkspace/application/import/nokia ui.zip. Example Thefollowingexampleshowsacompletebuild.xmlfile:


<project name="my-j2me-project" default="j2mepolish"> <!-- task definition --> <taskdef name="j2mepolish" classname="de.enough.polish.ant.PolishTask" classpath="import/enough-j2mepolishbuild.jar:import/jdom.jar:import/proguard.jar:import/retroguard.jar"/>

13

TheBuildProcess
<!-- optional J2ME apis --> <property name="polish.api.mmapi" location="/home/user/Nokia/Devices/Series_60/lib/ext/mma.zip" /> <property name="polish.api.wmapi" location="/home/user/Nokia/Devices/Series_60/lib/ext/wma.zip" /> <property name="polish.api.nokia-ui" location="/home/user/Nokia/Devices/Series_60/lib/ext/nokiaui.zip" /> <property name="polish.api.btapi" location="/home/user/Nokia/Devices/Series_60/lib/ext/bluetooth.zip" /> <!-- 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="notest" > <property name="test" value="false" /> </target> <target name="init"> <property name="test" value="true" /> </target> <target name="j2mepolish" depends="init"> <j2mepolish> <!-- general settings --> <info license="GPL" name="SimpleMenu" version="1.3.4" description="A test project" vendorName="enough software" infoUrl="http://www.enough.de/dictionary" icon="dot.png" jarName="${polish.vendor}-${polish.name}-example.jar" jarUrl="${polish.jarName}" copyright="Copyright 2004 enough software. All rights reserved." deleteConfirm="Do you really want to kill me?" /> <!-- selection of supported devices --> <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> <!-- build settings --> <build symbols="showSplash, AnotherExampleSymbol" imageLoadStrategy="background" fullscreen="menu" usePolishGui="true" preverify="/home/user/WTK2.1/bin/preverify" > <!-- midlets definition -->

14

TheBuildProcess
<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 unless="test" enable="true" name="ProGuard" /> <!-- debug settings: only debug when test is true --> <debug if="test" enable="true" visual="false" verbose="true" level="error"> <filter pattern="de.enough.polish.dict.*" level="debug" /> <filter pattern="de.enough.polish.ui.*" level="warn" /> </debug> </build> </j2mepolish> </target> <target name="clean"> <delete dir="build" /> <delete dir="dist" /> </target> </project>

InthefirstsectiontheJ2MEPolishtaskandthelocationsofsomeoptionalAPIsaredefined, followedbythebuildtargetsnotest,init,j2mepolishandclean.Thetargetsnotestand initareresponsibleforenteringthetestmode. IfyoucallAntwithoutanyarguments,theAntpropertytestwillbesettotrueintheinittarget. IfyoucallAntwiththeargumentsnotestj2mepolish,thetestpropertywillbesettofalse.This allowscontrollingthebuildscriptwithoutchangingit.Intheexampletheoptimizationisonlydone forthedeviceNokia/6600whenthetestpropertyistrue.Alsothedebugmessagesareonlyincluded whentestistrue.Theobfuscationwillonlybedonewhentestisfalse. Youcanforceacompleterebuildbycallingantclean.Thiscanbenecessaryafteryoumade changestothedevicedatabase. TheinfoSection Intheinfosectiongeneralinformationabouttheprojectisdefined.
<info license="GPL" name="SimpleMenu" version="1.3.4" description="A test project" vendorName="enough software" infoUrl="http://www.enough.de/dictionary" icon="dot.png" jarName="${polish.vendor}-${polish.name}-example.jar" jarUrl="${polish.jarName}" copyright="Copyright 2004 enough software. All rights reserved." deleteConfirm="Do you really want to kill me?" />

The<info>elementsupportsfollowingattributes: 15

TheBuildProcess infoAttribute Required license Yes Explanation Thelicenseforthisproject.EitherGPLwhenthesourcecodeofthe applicationispublishedundertheGNUGeneralPublicLicense,orthe commerciallicensekey,whichcanbeobtainedatwww.j2mepolish.org. Thenameoftheproject Theversionoftheprojectintheformat[major].[minor].[build]. Example:version=2.1.10. Thedescriptionoftheproject.Abriefexplanationaboutwhatthis applicationdoesshouldbegivenhere. Thenameofthevendorofthisapplication. Thenameofthejarfileswhichwillbecreated.Youcanusefollowing variables:
${polish.vendor}:Thevendorofthedevice,e.g.Samsungor

name version description vendorName jarName

Yes Yes Yes Yes Yes

Motorola
${polish.name}:Thenameofthedevice ${polish.identifier}:Vendoranddevicename,e.g.Nokia/6600 ${polish.version}:Theversionoftheprojectasdefinedabove.

Example:jarName=Game-${polish.vendor}-${polish.name}.jar resultsintoGameNokia6600.jarforanapplicationwhichhasbeen optimizedfortheNokia/6600. jarUrl Yes TheURLfromwhichthejarfilecanbedownloaded.Thisiseitherthe HTTPaddress,orjustthenameofthejarfile,whenitisloadedlocally. ApartfromthevariablesavailableforthejarNameattribute,youcan usethenameofthejarfileasdefinedabove: jarUrl=http://www.enough.de/midlets/Game/$
{polish.vendor}/${polish.name}/${polish.jarName}

copyright

No

Copyrightnotice. Thetextwhichispresentedtotheuserwhenhetriestodeletethe application. AHTTPURL,whichshouldbecalledafterthesuccessfulinstallation oftheapplication..Thiscanbeusefulfortrackinghowmany applicationsareinstalled,forexample.Theusercanpreventtheinstall notify,though.OnecanusethesamevariablesasforthejarUrl attribute. AHTTPURL,whichshouldbecalledaftertheapplicationhasbeen deletedfromthedevice.SeetheexplanationofinstallNotify. Theminimumspacewhichisneededonthedevice,e.g. dataSize=120kb.

deleteConfirm No installNotify No

deleteNotify dataSize

No No

16

TheBuildProcess

ThedeviceRequirementsSection 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 (bydefiningitwith<property name="test" value="true" />),onlytheupper <deviceRequirements>elementisusedandthesecond<deviceRequirements>elementisignored. Theactualrequirementsaredefinedwiththesubelements<requirement>.Withoutany clarification,alllistedrequirementsneedtobefulfilledbythedevicetobeselected.Thereare<or>, <and>,<not>and<xor>elements,whichcanbeusedtodefinetherequirementsveryflexible. deviceRequirements Required Attribute if unless No No Explanation ThenameoftheAntpropertywhichneedstobetrueoryes tousethis<deviceRequirements>. ThenameoftheAntpropertywhichneedstobefalseorno tousethis<deviceRequirements>. Explanation Therequirementwhichneedstobefulfilledbythedevice Seriesofrequirements,ofwhichallneedtobefulfilled. Seriesofrequirements,ofwhichatleastoneneedstobefulfilled. Seriesofrequirements,ofwhichoneneedstobefulfilled. Seriesofrequirements,ofwhichnonemustbefulfilled.

deviceRequirements Required Element requirement and or xor not Yes No No No No

Theactualworkisdonebythe<requirement>element: requirement Attribute name value Required Yes Yes Explanation Thenameoftheneededcapability,e.g.BitsPerPixel. Theneededvalueofthecapability,e.g.4+foracolordepthor atleast4bitsperpixel. 17

TheBuildProcess requirement Attribute type Required No Explanation 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" /> <and> <requirement name="JavaPackage" value="mmapi" /> <requirement name="JavaPlatform" value="MIDP/2.0+" /> </and> </or> </deviceRequirements>

Inthisexampleeachsupporteddevicemusthaveacolordepthofatleast4bitsperpixel. AdditionallythedeviceneedstosupporteithertheNokiaUIAPIandtheMobileMediaAPI (mmapi),ortheMobileMediaAPIandtheMIDP/2.0platform. Followingcapabilitiescanbecheckeddirectly: requirementname BitsPerPixel Explanation 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+" />

18

TheBuildProcess requirementname CanvasSize Explanation RequiredwidthandheightoftheMIDPCanvas.Somedevicesdonotallow theusageofthecompletescreen.


<requirement name="CanvasSize" value="120+ x 100+" />

JavaPlatform JavaPackage JavaProtocol HeapSize Vendor Identifier Feature

Theneededplatform,e.g.MIDP/1.0orMIDP/2.0+.
<requirement name="JavaPlatform" value="MIDP/2.0+" />

NeededAPIs,e.g.nokiaui,mmapi:
<requirement name="JavaPackage" value="nokia-ui, mmapi" />

Neededdataexchangeprotocols,e.g.serial,socket:
<requirement name="JavaProtocol" value="serial,socket" />

Theneededheapsizeofthedevice,e.g.200+kbor1.1+MB
<requirement name="HeapSize" value="200+kb" />

Thevendorofthedevice,e.g.NokiaorSiemens.
<requirement name="Vendor" value="Nokia, SonyEricsson" />

Theidentifierofthedevice,e.g.Nokia/6600.
<requirement name="Identifier" value="Nokia/6600, SonyEricsson/P900" />

Afeaturewhichneedstobesupportedbythedevice.
<requirement name="Feature" value="supportsPointer" />

ThebuildSection Withthe<build>sectiontheactualbuildprocessiscontrolled:
<build symbols="showSplash, AnotherExampleSymbol" imageLoadStrategy= "background" fullscreen="menu" usePolishGui="true" preverify="/home/user/WTK2.1/bin/preverify" > <!-- 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 unless="test" enable="true" name="ProGuard" /> <!-- debug settings: only debug when test is true --> <debug if="test" enable="true" visual="false" verbose="true" level="error"> <filter pattern="de.enough.polish.dict.*" level="debug" /> <filter pattern="de.enough.polish.ui.*" level="warn" /> </debug> </build>

19

TheBuildProcess AttributesofthebuildSection Thebuildsectionhasfollowingattributes: buildAttribute preverify Required Yes Explanation ThepathtothepreverifyexecutableoftheWirelessToolkit.The programisusuallywithinthebinfolderoftheWireless Toolkit. Thepathtothesourcedirectory.Thedefaultpathiseither source/src,sourceorsrc.Youcandefineseveralpathsby separatingthemwithacolon':'orasemicolon';': [path1]:[path2] ThedirectorycontainingthesourcesofJ2MEPolish.Defaultsto theenoughj2mepolishbuild.jar. Projectspecificsymbols,e.g.showSplashwhichcanbe checkedwith//#ifdefshowSplashinthesourcecode.Several symbolsneedtobeseparatedbycomma. DefineswhethertheJ2MEPolishGUIshouldbeusedatall. Possiblevaluesaretrueorfalse.EveniftheGUIshouldbe used,itwillbeusedonlyfordeviceswhichhavethenecessary capabilities(e.g.acolordepthofatleast8bits).Defaultvalueis true. Defineswhetherthecompletescreenshouldbeusedfordevices whichsupportafullscreenmode.Currentlytheseincludeonly deviceswhichsupporttheNokiaUIAPI.Possiblevaluesare eitherno,yesandmenu.Withyesthecompletescreen isusedbutnocommandsaresupported.Withmenu commandscanbeusedaswell.Defaultsettingisno. Thestrategyforloadingpictures.Possiblevaluesareeither foregroundorbackground.Theforegroundstrategyloads imagesdirectlywhentheyarerequested.Thebackground strategyloadstheimagesinabackgroundthread.Withthe backgroundstrategythefeltperformanceofanapplicationcan beincreased,butnotallpicturesmightbeshownrightaway whentheuserentersascreen.Thedefinitionofthe imageLoadStrategymakesonlysensewhentheJ2MEPolish GUIisused(usePolishGui=true).Defaultstrategyis foreground.Whentheforegroundstrategyisused,the preprocessingsymbolpolish.images.directLoadwillbe defined.Whenusingthebackgroundstrategy,thesymbol polish.images.backgroundLoadisdefined. Pathtothedevices.xmlfile.Defaultstodevices.xmlinthe currentfolderorinenoughj2mepolishbuild.jar. 20

sourceDir

No

polishDir symbols

No No

usePolishGui

No

fullscreen

No

imageLoadStrategy

No

devices

No

TheBuildProcess buildAttribute groups vendors apis midp1Path midp2Path workDir destDir apiDir resDir Required No No No No No No No No No Explanation Pathtothegroups.xmlfile.Defaultstogroups.xmlinthecurrent folderorinenoughj2mepolishbuild.jar. Pathtothevendors.xmlfile.Defaultstovendors.xmlinthe currentfolderorinenoughj2mepolishbuild.jar. Pathtotheapis.xmlfile.Defaultstoapis.xmlinthecurrent folderorinenoughj2mepolishbuild.jar. PathtotheMIDP/1.0API.Defaultstoimport/midp1.jar. PathtotheMIDP/2.0API.Defaultstoimport/midp2.jar. Thetemporarybuildfolder.Defaultstobuild. Thefolderintowhichthereadytodeployapplicationbundles shouldbestored.Defaultstodist. ThefolderinwhichtheAPIsarestored,defaultstoimport. Thefolderwhichcontainsalldesigndefinitionsandother resourceslikeimages,moviesetc.Bysettingadifferentfolder, completelydifferentdesignscanbedemonstrated.Defaultfolder isresources. Eithertrueorfalse.Defineswhethertheapplicationsshould beobfuscated.Defaultstofalse.Alternativelythenested elementobfuscatorcanbeused(seebelow). Thenameoftheobfuscator.DefaultstoProGuard. Alternativelythenestedelementobfuscatorcanbeused(see below).

obfuscate

No

obfuscator

No

ElementsofthebuildSection Thebuildsectionsupportsseveralnestedelements:<midlet>,<midlets>,<obfuscator>,<variables> and<debug>.


<midlet>and<midlets>

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

midletAttribute class name

Required Yes No

Explanation ThecompletepackageandclassnameoftheMIDlet. ThenameoftheMIDlet.Defaultistheclassnamewithoutthe package:TheMIDletcom.company.SomeMidletisnamed SomeMidletbydefault.

21

TheBuildProcess midletAttribute icon number Required No No Explanation TheiconofthisMIDlet.Whennoneisdefined,theicondefined inthe<info>sectionwillbeused.

ThenumberofthisMIDlet.ThisisinterestingonlyforMIDlet suitesinwhichseveralMIDletsarecontained. Theoptional<midlets>elementisusedasacontainerforseveral<midlet>elements:


<midlets> <midlet class="de.enough.polish.example.ExampleMidlet" /> <midlet name="J2ME Polish Demo" number="2" icon="no2.png" class="de.enough.polish.example.GuiDemoMidlet" /> </midlets>

<obfuscator>

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

obfuscatorAttribute Required enable if unless name No No No No

Explanation Eithertrueorfalse.Defaultstofalse.Obfuscatingwill onlybeactivatedwhenenable=true. ThenameoftheAntproperty,whichneedstobetrueoryes, whenthis<obfuscator>elementshouldbeused. ThenameoftheAntproperty,whichneedstobefalseorno, whenthis<obfuscator>elementshouldbeused. Thenameoftheobfuscatorwhichshouldbeused.Defaultsto ProGuard.Pleaseconsiderthelicenseagreementofthe obfuscator.TheProGuardobfuscatorislicensedundertheGNU GeneralPublicLicense.TheRetroGuardobfuscatorislicensed undertheGNULesserGeneralPublicLicense. Theclasswhichcontrolstheobfuscator.Eachclasswhich extendsde.enough.polish.obfuscate.Obfuscator canbe used.Withthismechanismthirdpartyobfuscatorscanbe integratedeasily.

class

No

The<obfuscator>supportsthesubelement<keep>,whichisusedtodefineclasseswhichareloaded dynamically(e.g.withClass.forName(...))andshouldnotbeobfuscated:
<obfuscator unless="test" enable="true" name="ProGuard" > <keep class="com.company.dynamic.SomeDynamicClass" /> <keep class="com.company.dynamic.AnotherDynamicClass" /> </obfuscator>

22

TheBuildProcess keepAttribute class Required Yes Explanation Thefullnameoftheclasswhichshouldnotgetobfuscated.

TheusedMIDletclassesdonotneedtobesetwiththe<keep>element,sincetheyaresavedfrom obfuscationautomatically.
<variables>

Theoptional<variables>elementcontainsseveralvariabledefinitions,whichcanbeusedforthe preprocessing.Thismechanismcanbeusedforexampletodefineconfigurationvalues:
<variables includeAntProperties="true"> <variable name="update-url" value="http://www.enough.de/update" /> </variables>

variablesAttribute

Required

Explanation Eithertrueorfalse.WhentrueallAntpropertieswillbe includedandcanbeusedinthepreprocessing.Defaultsto false.

includeAntProperties No

The<variables>elementcontainsanarbitrarynumberof<variable>elements,whichdefinethe actualvariables.Eachvariablehastheattributesnameandvalue: variableAttribute name value Required Yes Yes Thenameofthevariable. Thevalueofthevariable. Explanation

Variableswhichhavebeendefinedinthiswaycanbeincludedintothesourcecodewiththe//#= preprocessingdirective:
//#ifdef update-url:defined //#= String url = "${ update-url }"; //#else String url = "http://www.default.com/update"; //#endif

<debug>

Theoptional<debug>elementcontrolstheinclusionofdebuggingmessagesforspecificclassesor packages.Thedebuggingmessageswillbeactivatedordeactivatedinthesourcecode,sothe performancewillnotbedecreased,whenthedebuggingisdeactivated.


<debug enable="true" useGui="true" verbose="false" level="error"> <filter pattern="com.company.package.*" level="info" /> <filter pattern="com.company.package.MyClass" level="debug" /> </debug>

23

TheBuildProcess Inthesourcecodeanydebugmessagesmustbeaccompaniedbya//#debugdirective:
//#debug System.out.println("initialization done." );

or
//#debug warn System.out.println("could not load something..." );

InthechapterTheworldofpreprocessingonpage30youwillfindmoreaboutthedebugging possibilities. debugAttribute enable level Required No No Explanation Eithertrueorfalse.Debuggingmessageswillonlybe included,whentrueisgiven. Thegeneraldebuglevelwhichisneededfordebugmessages. Possiblevaluesaredebug,info,warn,error,fatalora userdefinedlevel.Defaultlevelisdebug,soalldebugging messageswillbeincluded. Eithertrueorfalse.Whentruethetime,classnameand linenumberwillbeincludedineachdebuggingmessage. Defaultstofalse.Whentheverbosemodeisenabled,the preprocessingsymbolpolish.debugVerbosewillbedefined. IntheverbosemodeexceptionsthrownbyJ2MEPolishwill containusefulinformation.Alsothekeyhandlingand animationhandlingwillbemonitoredanderrormessageswillbe givenout. useGui No Eithertrueorfalse.Whentruealldebuggingmessages, whicharepassedtothetoolde.enough.polish.util.Debug willbemadeavailableinaform.Thiscanbeusedtoshow debuggingmessagesonarealdevice.Defaultstofalse.When thevisualmodeisactivated,thepreprocessingsymbol polish.useDebugGuiwillbedefined. ThenameoftheAntproperty,whichneedstobetrueoryes, whenthis<debug>elementshouldbeused. ThenameoftheAntproperty,whichneedstobefalseorno, whenthis<debug>elementshouldbeused.

verbose

No

if unless

No No

Forafinercontrolofthedebuggingprocess,the<debug>elementallowsthesubelement<filter>, whichdefinesthedebuglevelforspecificclassesorpackages. filterAttribute pattern Required Yes Explanation Thenameoftheclassorofthepackage.Whenthepatternends withastar,allclassesofthatpackagewillbeincluded,e.g. com.company.mypackage.*

24

TheBuildProcess filterAttribute level Required Yes Explanation Thedebugginglevelforallclasseswiththespecifiedpattern. Possiblevaluesaredebug,info,warn,error,fatalora userdefinedlevel.

25

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 Capabilitiesonpage10.

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. Ifavariableisdefined,itcanbecheckedvia//#ifdef [variable]:defined :


//#ifdef polish.ScreenSize:defined

26

TheWorldofPreprocessing Directive //#ifdef[symbol] Meaning if[symbol]isdefined Explanation Thesymbolnamed[symbol]needstobe defined,whenthenextsectionshouldbe compiled. Thesymbolnamed[symbol]mustnotbe defined,whenthenextsectionshouldbe compiled. Whentheprevioussectionwasfalse,the followingsectionwillbecompiled(and theotherwayround). Thesymbolnamed[symbol]needstobe definedandtheprevioussectionneedsto befalse,whenthenextsectionshouldbe compiled.

//#ifndef[symbol]

if[symbol]isnotdefined

//#else

else

//#elifdef[symbol]

elseif[symbol]isdefined

//#elifndef[symbol]

elseif[symbol]isnotdefined Thesymbolnamed[symbol]mustnotbe definedandtheprevioussectionneedsto befalse,whenthenextsectionshouldbe compiled. endoftheifblock Endofeveryifdefandifndefblock.

//#endif

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. CheckSeveralSymbolsandVariableswith#if,#else,#elifund#endif Witheach#ifdefdirectiveonlyasinglesymbolcanbechecked.Withthe#ifand#elifdirectives, however,complextermscontainingseveralsymbolsandvariablescanbeevaluated:


//#if useEnhancedInput && (polish.pointerSupported || polish.mouseSupported) doSomething(); //#endif

27

TheWorldofPreprocessing #ifdirectivescanalsobenestedandcontainotherpreprocessingdirectiveslikethe#ifdefdirectives. #ifand#ifdefdirectivescanalsobemixed:


//#if !basicInput && (polish.pointerSupported || polish.mouseSupported) doSomething(); //#if polish.BitsPerPixel >= 8 doSomethingColorful(); //#else doSomethingDull(); //#endif //#elifdef doWildStuff doWildStuff(); //#endif

Directive //#if[term] //#else

Meaning if[term]istrue else

Explanation Thespecifiedtermmustbetrue,whenthe nextsectionshouldbecompiled. Whentheprevioussectionwasfalse,the followingsectionwillbecompiled(and theotherwayround). Thespecifiedtermneedstobetrueandthe previoussectionneedstobefalse,when thenextsectionshouldbecompiled. Endofeveryifblock.

//#elif[term]

elseif[term]istrue

//#endif

endoftheifblock

Inthetermsthebooleanoperators&&,||,^and!canbeused.Complextermscanbeseparated usingnormalparenthesizes(and).Thetermargumentsforbooleanoperatorsaresymbols, whicharetruewhentheyaredefinedandfalseotherwise. Variablescanbecheckedwiththecomparator==,>,<,<=and>=.Argumentsforthecomparators arevariablesorconstants. Atermcanincludecomparatorsandbooleanoperators,whenthesectionsareseparatedby parenthesizes. BooleanOperator Meaning && || ^ and or xor Explanation Botharguments/symbolsneedtobedefined:
true && true = true true && false = false && true = false && false = false

Atleastoneargument/symbolmustbedefined:
true || true = true || false = false || true = true false || false = false

Onlyandatleastoneargument/symbolmustbedefined:
true ^ false = false ^ true = true true ^ true = false ^ false = false

28

TheWorldofPreprocessing BooleanOperator Meaning ! not


! false = true ! true = false

Explanation Theargument/symbolmustnotbedefined:

Comparator ==

Meaning equals

Explanation Theleftandtherightargumentmustbeequal,integersandstringscan becompared:


8 == 8 = true Nokia == Nokia = true //#if polish.BitsPerPixel == 8 //#if polish.vendor == Nokia

>

greater

Theleftargumentmustbegreaterthantherightone.Onlyintegerscan becompared:
8 > 8 = false 16 > 8 = true //#if polish.BitsPerPixel > 8

<

smaller

Theleftargumentmustbesmallerthantherightone.Onlyintegers canbecompared:
8 < 8 = false 8 < 16 = true //#if polish.BitsPerPixel < 8

>=

greateror equals

Theleftargumentmustbegreaterthanorequalstherightone.Only integerscanbecompared:
8 >= 8 = true 16 >= 8 = true //#if polish.BitsPerPixel >= 8

<=

smalleror Theleftargumentmustbesmallerthanorequalstherightone. equals Onlyintegerscanbecompared:


8 <= 8 = true 8 <= 16 = false //#if polish.BitsPerPixel <= 8

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 29

TheWorldofPreprocessing 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#debug directive.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.getMessage() ); //#enddebug

Directive //#debug[level]

Explanation Thenextlineisonlycompiledwhenthedebuggingsettingfortheclassin whichthedebugginginformationisenabledforthespecifiedlevel.When nolevelisspecified,thedebuglevelisassumed. Thenextlinesuptothe#enddebugdirectivewillbecompiledonlywhen thedebuggingsettingfortheclassinwhichthedebugginginformationis enabledforthespecifiedlevel.Whennolevelisspecified,thedebug levelisassumed. Markstheendofthe#mdebugsection.

//#mdebug[level]

//#enddebug DebugLevels

Followingdebuglevelsarepredefined: debug,info,warn,errorandfatal.Thespecificlevelforaclasscanbedefinedwiththe <debug>elementoftheJ2MEPolishtask:


<debug enable="true" useGui="true" verbose="false" level="error"> <filter pattern="com.company.package.*" level="info" /> <filter pattern="com.company.package.MyClass" level="debug" />

30

TheWorldofPreprocessing
</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 System.out.println("complex method took [" + (System.currentTimeMilis() startTime) + "] ms.");

TheDebugUtilityClass Theutilityclassde.enough.polish.util.Debugcanbeusedfordebugging.Itisespeciallyusefulfor theGUIdebuggingmode,whichcanbeenabledinthebuild.xmlbysettingtheuseGuiattribute ofthe<debug>elementtotrue:


<debug enable="true" useGui="true" verbose="false" level="error"> <filter pattern="com.company.package.*" level="info" /> <filter pattern="com.company.package.MyClass" level="debug" /> </debug>

Itsdebugmethodsareusedtoeitherprintoutthedebugmessagestothestandardoutput,ortostore themessagesinaform,whichcanbeshownonarealdevice.Thisisespeciallyusefulfortracking errorsonarealhandset:


import de.enough.polish.util.Debug; [...] try { callComplexMethod(); //#debug info Debug.debug( "complex method succeeded." ); } catch (MyException e) { //#debug error Debug.debug( "complex method failed", e ); }

Bothdebugmethodsareusedintheexample.Thesecondmethoddebug(String,Throwable)also printsoutthestacktraceoftheexception,whentheGUIdebuggingmodeisnotenabled. YoucanmakethedebuginformationavailableinyourMIDletclasswiththefollowingcode:


import de.enough.polish.util.Debug; public class MyMIDlet extends MIDlet { //#ifdef polish.useDebugGui private Command logCmd = new Command( "show log", Command.SCREEN, 10 ); //#endif private Screen mainScreen; [...] public MyMIDlet() {

31

TheWorldofPreprocessing
[...] //#ifdef polish.useDebugGui this.mainScreen.addCommand( this.logCmd ); //#endif

} public void commandAction(Command cmd, Displayable screen ) { [...] //#ifdef polish.useDebugGui if (cmd == logCmd) { this.display.setCurrent( Debug.getLogForm( true, this ) ); } else if (cmd == Debug.RETURN_COMMAND) { this.display.setCurrent( this.mainScreen ); } //#endif }

IntheaboveexampletheMIDletMyMIDletaddsacommandtoitsmainscreenwhentheGUI debuggingmodeisenabled.Whenthisisthecase,thepreprocessingsymbolpolish.useDebugGui willbedefined.Theusercanthenselecttheshowlogcommandtoseetheformwithalllogging messages.Whentheuserselectsthereturncommandfromthelogscreen,hewillreturntothe mainscreen. Pleasemakesure,thatyouhaveaddedtheimport/enoughj2mepolishutil.jartotheclasspathof yourproject,whenusingtheDebugclass. DebugMethod/DebugField Debug.debug(Stringmessage) Explanation WhentheGUIdebuggingmodeisactivated,thegiven messagestringwillbeaddedtothelistofmessages. Otherwisethemessagewillbeprintedtothestandardoutput viaSystem.out.println(String). WhentheGUIdebuggingmodeisactivated,thegiven messagestringwillbeaddedtothelistofmessages. Otherwisethemessageandthestacktraceoftheexception willbeprintedtothestandardoutput. RetrievestheFormwhichcontainsalllogmessages.When reverseistrue,thelastlogmessagewillbeonthetopofthe form.Thismethodisonlyavailable,whentheGUIdebugging modeisenabled. Thecommandwhichisalwaysaddedthetheloggingform. Thisfieldisonlyavailable,whentheGUIdebuggingmodeis enabled.

Debug.debug(Stringmessage, Throwableexception)

Debug.getLogForm(boolean reverse,CommandListener listener) Debug.RETURN_COMMAND

UsingVariableswith#= Youcanaddthecontentsofvariableswiththe#=directive:
//#= private String url = ${ start-url };

Whenthevariableisnotdefined,theaboveexamplewouldthrowanexceptionduringthe preprocessingstepofthebuildprocess.Youcanusethe[variable]:definedsymbol,whichisset foreveryknownvariable: 32

TheWorldofPreprocessing
//#ifdef start-url:defined //#= private String url = ${ start-url }; //#else private String url = "http://192.168.101.101"; //#endif

Thisisespeciallyusefulforsettingconfigurationvalues,whichcanchangeeasily,likeWebURLs andsoon. Thenameofthevariableneedstobesurroundedbya${},justlikereferringtoAntpropertiesinthe build.xml. Variablescanbedefinedinthe<variables>elementinthebuild.xml.Othervariablesaredefinedin thedevices.xml,vendors.xmlandgroups.xmlbythecapabilitiesofthedevices,vendorsandgroups. 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.Thestylesmentionedherecanbedefinedinthe resources/polish.cssfile.Inthatfilethestylenamesneedtostartwithadot.Intheaboveexample youcandefinethestyles.cool,.frostyordefault.Thedefaultstyleisapredefinedstyleand itsnamemustnot,therefore,startwithadot. Stylesareonlyused,whentheJ2MEPolishGUIisused.Thiscanbetriggeredwiththe usePolishGuiattributeofthe<build>elementinthebuild.xml. Using#styledirectiveimprovestheperformanceoftheapplication,sincedynamicstylesneedsome processingtime.Dynamicstylesdesignitemsbytheirpositioninscreens,seesectionDynamic Stylesonpage41. Stylescanbesetforallitemsconstructorsandformanymethods: InsertionPoint Itemconstructors Example
//#style cool, frosty, default StringItem url = new StringItem ( null, "http://192.168.101.101" ); //#style cool ImageItem img = new ImageItem ( null, iconImage, ImageItem.LAYOUT_DEFAULT, null );

Explanation The#styledirectivecanbe placedbeforeanyitem constructor.

33

TheWorldofPreprocessing InsertionPoint Example Explanation The#styledirectivecanbe placedbeforecallingthe setAppearanceModemethodof anItem.Pleasenote,thatthis methodisonlyavailablein J2MEPolish.
);

//#style openLink Item. url.setAppearanceMode setAppearanceMode ( Item.HYPERLINK ); ()

List.append()

//#style choice list.append( "Start", null

The#styledirectivecanbe placedbeforeaddingalist element.


);

List.insert()

//#style choice list.insert( 2, "Start", null

The#styledirectivecanbe placedbeforeinsertingalist element. The#styledirectivecanbe placedbeforesettingalist element. The#styledirectivecanbe placedbeforeaddingan elementtoaChoiceGroup. The#styledirectivecanbe placedbeforeinsertingan elementtoaChoiceGroup.

List.set()

//#style choice list.set( 2, "Start", null

);

ChoiceGroup.appen //#style choice group.append( "Choice 1", null ); d() ChoiceGroup.insert () ChoiceGroup.set()
//#style choice group.insert( 2, "Choice 3", null ); //#style choice group.set( 2, "Choice 3", null

);

The#styledirectivecanbe placedbeforesettinganelement ofaChoiceGroup.

ExcludeorIncludeCompleteFileswith#condition The#conditiondirectivecanbeusedtopreventtheusageofcompletefiles,whenaconditionisnot met:


//#condition polish.usePolishGui

WhenintheaboveexampletheJ2MEPolishGUIisnotused(andthusthesymbol polish.usePolishGuiisnotdefined),thefilewillnotbeincludedintotheapplicationbundleforthe currentdevice.Conditionscanusethesameoperatorsandcomparatorslikethe#ifdirective. DefiningTemporarySymbolswith#defineand#undefine Youcantemporarilydefineandundefinesymbolsaswell.Thiscanbeusedtoevaluateacomplex iftermonlyonceandthenreferringasimplesymbolinsteadofusingthecomplextermagain:


//#if !basicInput && (polish.pointerSupported || polish.mouseSupported) //#define tmp.complexInput //#endif

34

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

Directive //#define[symbol] //#undefine[symbol]

Explanation Definesthespecifiedsymbol.Youcanneverdefinethesymbolfalse. Removesthespecifiedsymbolfromthepoolofdefinedsymbols.Youcan neverundefinethesymboltrue.

Pleasenotethatyoushouldrelyonadefinedorundefinedsymbolonlyinthesamesourcefile whereyoudefinedorundefinedthatsymbol.Itisadvisedthatyoustartthenamesofdefined symbolswithtmp.,sothatyoualwaysknowthatthisisatemporarysymbol. InsertingCodeFragmentswith#include Youcaninsertcompletecodefragmentswiththe#includedirective:


//#include ${polish.source}/includes/myinclude.java

Withinthefilenameyoucanusealldefinedvariables.Ausefulvariableisespecially polish.source,whichpointsthebasedirectoryofthefile,whichiscurrentlypreprocessed.Iyou useonlyrelativenames,pleasebearinmind,thatthebasedirectoryistherootofyourproject(orto bemoreprecise:thedirectorywhichcontainsthebuild.xmlfile). 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. J2MEPolishSymbols Dependingonthesettingsinthebuild.xmldifferentsymbolswillbedefined.Pleasecomparethe TheBuildSection,page19. UsefulVariables PleaserefertothesectionCapabilitiesonpage10forstandardpreprocessingvariables. Othervariablesinclude:

35

TheWorldofPreprocessing

polish.animationInterval definestheintervalinmillisecondsforanimations.Thisdefaultsto

100ms,butyoucanchangethisvaluewithinthe<variables>elementofthe<build>section.

polish.classes.fullscreen definesthenameofthefullscreenclass,whenthedevicesupports

suchaclass.FordeviceswhichsupporttheNokiaUIAPIthisvariablecontains com.nokia.mid.ui.FullCanvas.Followingexampleillustratestheusage:
public abstract class MyCanvas //#if polish.useFullScreen && polish.classes.fullscreen:defined //#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.

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

36

TheJ2MEPolishGUIforDesigners

TheJ2MEPolishGUIforDesigners
J2MEPolishincludesanoptionalGraphicalUserInterface,whichcanbedesignedusingtheweb standardCascadingStyleSheets(CSS).Soeverywebdesignercannowdesignmobileapplications thankstoJ2MEPolish!Thischapterwillexplainalldetailsofthedesignpossibilities,noprior knowledgeaboutCSSisrequired.1TheGUIiscompatiblewiththejavax.microedition.uiclasses, thereforenochangesneedtobemadeinthesourcecodeoftheapplication.TheGUIwillbe incorporatedbythepreprocessingmechanismautomatically,unlesstheusePolishGuiattributeof the<build>elementissettofalseinthebuild.xmlfile. AQuickGlance Alldesignsettingsandfilesarestoredintheresourcesdirectoryoftheproject,unlessanother directoryhasbeenspecified.2Themostimportantfileispolish.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; }

InthisexamplethestylecalledmyStyledefinessomefontvaluesandthecolorofthe background.Anystylecontainsaselectoraswellasanumberofattributesanditsvalues:
.myStyle { font-color: white; }

selector/nameattribute value
Fig.1:Structureofastyle

Eachattributevaluepairneedstobefinishedwithasemicolon.Thestyledeclarationneedstobe finishedbyaclosingcurvedparenthesis.Theselectorornameofstyleiscaseinsensitive,so .MySTYleisthesameas.myStyle. Apartfromthepolish.cssfile,youcanputimagesandothercontentsintotheresourcesfolder. Subfoldersareusedforstylesandcontentforspecificdevicesandgroups.Youcanputall resourcesforNokiadevicesintotheNokiafolderandresourcesforSamsung'sE700intothe Samsung/E700folder.ThisisdescribedinmoredetailintheDesigningSpecificDevicesand DeviceGroupssection. YoucanspecifystylesdirectlyforGUIitemswiththe#stylepreprocessingdirectiveinthesource code.AlternativelyyoucanusethedynamicnamesoftheGUIitems,e.g.pfortextitems,afor hyperlinksorformpforalltextitemswhichareembeddedinaform.Thepossiblecombinations
1 Refertohttp://www.w3schools.com/css/foranexcellenttutorialofCSSforwebpages. 2 YoucanspecifythedirectorywiththeresDirattributeofthe<build>elementinthebuild.xmlfile.Thiscanbe usedtocreatecompletelydifferentdesignsforoneapplication.

37

TheJ2MEPolishGUIforDesigners aswellasthepredefinedstylenamesarediscussedinthesectionDynamic,StaticandPredefined Styles. Stylescanextendotherstyleswiththeextendskeyword,e.g..myStyleextendsbaseStyle{}.This processisdescribedinthesectionExtendingStyles. J2MEPolishsupportstheCSSboxmodelwithmargins,paddingsandcontent.Othercommon designsettingsincludethebackground,theborderandfontsettings.Thesecommonsettingsare describedinthesectionCommonDesignAttributes.AttributesforspecificGUIitemsaswellas thedetailsofthedifferentbackgroundandbordertypesarediscussedinthesectionSpecific DesignAttributes. DesigningforSpecificDevicesorDeviceGroups Sometimesthedesignneedstobeadaptedtoaspecificdeviceoragroupofdevices.Youcaneasily usespecificpictures,stylesetceterabyusingtheappropriatesubfoldersoftheresourcesfolder. TheHierarchyoftheresourcesFolder Intheresourcesfolderitselfyouputallresourcesanddesigndefinitionswhichshouldbevalidfor alldevices. 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 38

TheJ2MEPolishGUIforDesigners attributeofthatstyle.Nootherattributesorstylesneedtobedefined.Thisisthecascading 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.xml3.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
3 devices.xmlcaneitherbefoundintherootfolderoftheprojectorintheimport/enoughj2mepolishbuild.jarfile.

39

TheJ2MEPolishGUIforDesigners thatdeviceinthedevices.xmlfile.Dependingonhowmanybitsperpixelaresupported,thedevice belongstodifferentgroups: BitsperPixel 1 4 8 Colors 21=2(b/w) 24=16 28=256 Groups BitsPerPixel.1 BitsPerPixel.4 BitsPerPixel.4+ BitsPerPixel.8 BitsPerPixel.8+ BitsPerPixel.4+ BitsPerPixel.12 BitsPerPixel.12+ BitsPerPixel.8+ BitsPerPixel.4+ BitsPerPixel.16 BitsPerPixel.16+ BitsPerPixel.12+ BitsPerPixel.8+ BitsPerPixel.4+ BitsPerPixel.24 BitsPerPixel.24+ BitsPerPixel.16+ BitsPerPixel.12+ BitsPerPixel.8+ BitsPerPixel.4+

12

212=4.096

16

216=65.536

24

224=16.777.216

Soyoucanputimagesforphoneswithatleast16colorsintotheresources/BitsPerPixel.4+ folder.Andyoucanspecifysettingsfortruecolordevicesinthefile resources/BitsPerPixel.24/polish.css. Dynamic,StaticandPredefinedStyles J2MEPolishdistinguishesbetweendynamic,staticandpredefinedstyles:


PredefinedstylesareusedbytheGUIforseveralitemslikescreentitles. Staticstylesaredefinedinthesourcecodeoftheapplicationwiththe#stylepreprocessing directive. Dynamicstylesareusedforitemsaccordingtotheirpositiononthescreen.

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

TheJ2MEPolishGUIforDesigners Staticstylesarefasterthandynamicstyles.Itisthereforerecommendedtousestaticstyles wheneverpossible. PredefinedStyles PredefinedstylesarestaticstyleswhichareusedbytheJ2MEPolishGUI.Incontrasttothenormal userdefinedstaticstylestheirnamesdonotstartwithadot,e.g.titleinsteadof.title. Followingpredefinedstylesareused: Style title focused menu Thestyleofscreentitles. Thestyleofacurrentlyfocuseditem.ThisstyleisusedinLists,Forms andforContainersliketheChoiceGroup. Thisstyleisusedfordesigningthemenubarinthefullscreenmode. ThefullscreenmodecanbetriggeredbythefullScreenModeattribute ofthe<build>elementinthebuild.xml(with fullScreenMode=menu).Inthemenustyleyoucanalsodefinewhich styleisusedforthecurrentlyfocusedcommandwiththefocused styleattribute,e.g.focusedstyle:menuFocused;.Inthiscaseyou needtodefinethestaticstyle.menuFocusedaswell. Thestyleusedforthemenuitems(thecommands)ofascreen.When menuItemisnotdefined,themenustyleisusedinstead. ThestylewhichisusedbytheJ2MEPolishGUIwhenthedesired predefinedstyleisnotdefined.Thedefaultstyleisalwaysdefined,even whenitisnotexplicitlydefinedinthepolish.cssfile. Description

menuItem default

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;

41

TheJ2MEPolishGUIforDesigners
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,youcandesignallhyperlinks4inthescreen withthestyle.startScreenforexamplewiththefollowingstyledeclaration:
.startScreen a { font-color: blue; font-size: medium; font-style: italic; }

Itemsandscreenshavespecificselectorsfordynamicstyles: ItemClass StringItem p a button ImageItem Gauge Spacer img gauge spacer Selector Explanation StringItemshowstext.Thepselectorisused,whenthe itemhastheappearancemodePLAIN. Theaselectorisused,whentheitemhastheappearance modeHYPERLINK. Thebuttonselectorisused,whentheitemhasthe appearancemodeBUTTON. Showsanimage. Showsaprogressindicator. Isusedforshowinganemptyspace.TheusageoftheSpacer itemisdiscouraged,sincethespacescanbesetforallitems withthemarginandpaddingattributes. Showsanimagetogetherwithtext. Allowstextualinputfromtheuser. Allowstheinputofdatesortimesfromtheuser. Containsseveralchoiceitems.

IconItem TextField DateField ChoiceGroup

icon textfield datefield choicegroup

4 StringItemswhichhavetheappearancemodeItem.HYPERLINK

42

TheJ2MEPolishGUIforDesigners ItemClass ChoiceItem Selector listitem radiobox checkbox popup Explanation Showsasinglechoice.Theselectorlistitemisused,when thisitemiscontainedinanimplicitlist. Theselectorradioboxisusedwhenthelistorchoicegroup hasthetypeexclusive. Theselectorcheckboxisusedwhenthelistorchoicegroup hasthetypemultiple. Theselectorpopupisusedwhenthechoicegrouphasthe typepopup. Explanation Showsseveralchoiceitems. ContainsdifferentGUIitems. Containsasingletextfield.

ScreenClass List Form TextBox ExtendingStyles list

Selector form textbox

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 { 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 { /* this extends is invalid! */

43

TheJ2MEPolishGUIforDesigners
font-color: white; background-color: black;

Theaboveexamplewouldbevalid,whenthestylebaseScreenwouldnotextendthe highscoreScreenstyle. CSSSyntax FollowingrulesdoapplyforCSSstyles: StructureofaCSSDeclaration


.myStyle { font-color: white; }

selector/nameattribute value
Fig.2:Structureofastyle

Everystylestartswiththeselectorfollowedbyanopeningcurvedparenthesis,anumberof attributevaluepairsandaclosingcurvedparenthesis. Theselectorcanconsistofseveralitemnamesandcontainanextendsclause. 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. 44

TheJ2MEPolishGUIforDesigners 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; }

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:Theusedcontentfontanditscolor label:Theusedlabelfontanditscolor layout:Thelayoutoftheitems. background:Thedefinitionoftheitem'sbackground border:Thedefinitionoftheitem'sborder beforeandafter:Elementswhichshouldbeinsertedbeforeoraftertheitems. 45

TheJ2MEPolishGUIforDesigners

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 and label: */ font { color: blue; size: medium; face: system; } label { color: black; size: small; } /* layout is centered: */ layout: center; /* background: */ background-color: gray; /* no border: /* border: none; /* before: add an image: */ before: url( arrow.png ); /* after: add another image: */ after: url( leftArrow.png ); /* no specific attributes are used in this example*/ }

TheCSSBoxModel:MarginsandPaddings AllGUIitemssupportthestandardCSSboxmodel: margintop border paddingtop marginright marginleft content paddingright paddingleft

paddingbottom marginbottom

ThemargindescribesthegaptootherGUIitems.Thepaddingdescribesthegapbetweentheborder 46

TheJ2MEPolishGUIforDesigners 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:


.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 left right center expand horizontalcenter, hcenter horizontalexpand, hexpand AlternativeNames Explanation Theaffecteditemsshouldbeleftaligned. Theaffecteditemsshouldberightaligned. Theaffecteditemsshouldbecenteredhorizontally. Theaffecteditemsshouldusethewholeavailable width(i.e.shouldfillthecompleterow). 47

TheJ2MEPolishGUIforDesigners Layout shrink top bottom vcenter vexpand vshrink newlineafter AlternativeNames horizontalshrink, hshrink verticalcenter verticalexpand verticalshrink Explanation Theaffecteditemsshouldusetheminimumwidth possible. Theaffecteditemsshouldbetopaligned. Theaffecteditemsshouldbebottomaligned. Theaffecteditemsshouldbecenteredvertically. Theaffecteditemsshouldusethewholeavailable height(i.e.shouldfillthecompletecolumn). Theaffecteditemsshouldusetheminimumheight possible. Itemsfollowinganitemwithanewlineafterlayout shouldbeplacedonthenextline.Currentlythe newlinesettingswillbeignored,sinceeveryitem willbeplacedonanewline. Theaffecteditemsshouldalwaysstartonanewline (whenthereareanyitemsinfrontofit).Currently thenewlinesettingswillbeignored,sinceevery itemwillbeplacedonanewline. Nospecificlayoutshouldbeused,insteadthe defaultbehaviorshouldbeused.Suchalayoutdoes notneedtobedefinedexplicitly,butitcanbeuseful tooverwriteabasicsetting.

newlinebefore

plain

default,none

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: 48

TheJ2MEPolishGUIforDesigners
.myStyle { layout: hcenter | hexpand; }

Andequivalentwith:
.myStyle { layout: horizontal-center | horizontal-expand; }

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


PredefinedColors

The16standardwindowscolorsarepredefined: Color white black red lime blue green silver gray HexValue
#FFFFFF #000000 #FF0000 #00FF00 #0000FF #008000 #C0C0C0 #808080

Example

Color yellow maroon purple fuchsia olive navy teal aqua

HexValue
#FFFF00 #800000 #800080 #FF00FF #808000 #000080 #008080 #00FFFF

Example

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 */

49

TheJ2MEPolishGUIforDesigners
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. 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. FontsandLabels ManyGUIItemshavetextelements,whichcanbedesignedwiththefontorlabelattributes. Bothattributegroupssupportthesameattributes: Attribute color PossibleValues Explanation

Referencetoacolorordirectdeclaration Dependingonthenumberofcolorsthe ofthecolor. devicesupports,colorscanlook differentlyontheactualdevice.

50

TheJ2MEPolishGUIforDesigners Attribute face PossibleValues system(default,normal) Explanation Thedefaultfontfacewhichisused whenthefontfaceorlabelface attributeisnotset. Aproportionalface.Thisisonsome devicesactuallythesamefontfaceas thesystemfont. Afontfaceinwhicheachcharacterhas thesamewidth. Thesmallestpossiblefont. Thedefaultsizefortexts. Thelargestpossiblefontsize. Thedefaultstyle. Aboldthickstyle. Acursivestyle. Notreallyastyle,justanunderlined text.

proportional

monospace size small medium(default,normal) large(big) style plain(default,normal) bold italic(cursive) underlined

Anexamplefontandlabelspecification:
.myStyle { font-color: white; font-face: default; /* same as system or normal */ font-size: default; /* same as medium or normal */ font-style: bold; label-color: gray; label-face: proportional; label-size: small; label-style: cursive; /* same as italic */ }

Thesamespecificationcanalsobewrittenasfollows:
.myStyle { font { color: white; style: bold; } label { color: gray; face: proportional; size: small; style: cursive; /* same as italic */ } }

Inthefontdefinitiontheabovefaceandsizeattributescanbeskipped,sincetheyonlydefinethe defaultbehavioranyhow. 51

TheJ2MEPolishGUIforDesigners 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 {

52

TheJ2MEPolishGUIforDesigners
after: url( heart.png ); background: none; border-type: round-rect; border-arc: 6; border-color: yellow; border-width: 2; layout: left | expand; font-color: black;

Currentlyonlyimagescanbeincluded. SpecificDesignAttributes ManyGUIitemssupportspecificCSSattributes. Backgrounds


Fig.3:Theafterattributein action.

TherearemanydifferentbackgroundtypeswhichmakeuseofspecificCSSattributes.When anotherbackgroundthanthedefaultsimplebackgroundortheimagebackgroundshouldbeused, thebackgroundtypeattributeneedstobedeclared. Whennobackgroundatallshouldbeused,thebackground: none;declarationcanbeused.


SimpleBackground

Thesimplebackgroundjustfillsthebackgroundwithonecolor.Whennobackgroundtypeis specified,thesimplebackgroundisusedbydefault,unlessthebackgroundimageattributeisset. Inthelatercasetheimagebackgroundwillbeused. Thesimplebackgroundsupportsthecolorattribute: Attribute color Required Yes Explanation Thecolorofthebackground,eitherthenameofthecolororadirect definition.

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

RoundRectBackground

Theroundrectbackgroundpaintsarectangularbackgroundwithroundedges.Itsupportsfollowing attributes: Attribute type Required Yes Explanation Thetypeneedstoberoundrectorroundrect. 53

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

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

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

ImageBackground

Theimagebackgroundusesanimageforpaintingthebackground.Thisbackgroundtypeisusedby defaultwhennotypeissetandthebackgroundimageattributeisset.Thebackgroundsupports followingattributes: Attribute type color Required No No Explanation Whenusedneedstobeimage. Thecolorofthebackground,eitherthenameofthecolor,adirect definitionortransparent.Thedefaultcoloriswhite.Thiscolorcan onlybeseenwhentheimageisnotbigenough. TheURLoftheimage,e.g.url(background.png) Eitherrepeat,norepeat,repeatxorrepeaty.Determines whetherthebackgroundshouldberepeated,repeatedhorizontallyor repeatedvertically.Defaultisnorepeat.

image repeat

Yes No

54

TheJ2MEPolishGUIforDesigners Abackgroundimage,whichshouldnotberepeatedwillbecenteredautomatically.Thefollowing styleusestheimagebg.pngasabackground:


.myStyle { background-image: url( bg.png ); }

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

PulsatingBackground

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

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

Borders TherearemanydifferentbordertypeswhichmakeuseofspecificCSSattributes.Whenanother borderthanthedefaultsimplebordershouldbeused,thebordertypeattributeneedstobedeclared.

55

TheJ2MEPolishGUIforDesigners Whennoborderatallshouldbeused,theborder: none;declarationcanbeused.


SimpleBorder

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

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

RoundRectBorder

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

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

Thefollowingexampleusesadifferenthorizontalarcdiameter: 56

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

ShadowBorder

Theshadowborderpaintsashadowyborder.Followingattributesaresupported: Attribute type color width offset Required Yes Yes No No Explanation Thetypeneedstobeshadow,bottomrightshadoworright bottomshadow. Thecoloroftheborder,eitherthenameofthecolororadirect definition. Thewidthoftheborderinpixels.Defaultsto1. Theoffsetbetweenthecornerandthestartoftheshadow.Defaultsto 1pixel,whennoneisspecified.

Currentlyonlyabottomrightshadowissupported,sotheborderispaintedbelowtheitemand rightoftheitem. Thefollowingexampleusesagreenshadowborder:


.myStyle { border-type: shadow; border-color: purple; border-width: 2; border-offset: 2; }

Screens:List,FormandTextBox
PredefinedStylesforLists,FormsandTextBoxes

AllscreenshaveatitleandoneorseveralembeddedGUIitems.InaFormorListoneitemis usuallyfocused.Screenscanalsohaveadesignablemenu,whentheapplicationusesafullscreen mode(onNokiadevices)5.Someoftheusedstylescanalsouseadditionalattributes. StyleName title focused Add.Attributes Thetitleofascreen. Thestyleofthecurrentlyfocusediteminthescreen. Explanation

5 Thefullscreenmodecanbeactivatedbysettingthe<build>attributefullscreentoeithermenuoryesinthe build.xmlfile.

57

TheJ2MEPolishGUIforDesigners StyleName menu focusedstyle menubarcolor Add.Attributes Explanation Thestyleofthefullscreenmenu. Thenameofthestyleforthecurrentlyfocusedmenuitem. Thebackgroundcolorofthemenubar.Eitherthenameor thedefinitionofacolorortransparent.Defaultsto white.

labelcolor,label Thefontofthemenucommands(likeSelector face,labelsize, Cancel).Defaultcolorisblack,defaultfontisthe labelstyle systemfontinaboldstyleandmediumsize. menuItem Thestyleforthecommandsinthemenu.Whennot defined,themenustylewillbeused.

AdditionalAttributesforScreens

Eachscreenitselfcanhavesomeadditionalattributes: Attribute focusedstyle columns columnswidth Required No No No Explanation Thenameofthestyleforthecurrentlyfocusedmenuitem. Defaultstothepredefinedfocusedstyle. Thenumberofcolumns.Thiscanbeusedtolayouttheitemsin atable.Defaultsto1column. Eithernormal,equalorthewidthforeachcolumnina commaseparatedlist(e.g.columns-width: 60,60,100;). Defaultstonormal,meaningthateachcolumnusesasmuch spaceasthewidestitemofthatcolumnneeds. Theequalwidthleadstocolumnswhichhaveallthesame width. Theexplicitlistofcolumnwidthsresultsintheusageofthose widths.

58

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

DynamicStylesforScreens

Dynamicstylescanbeusedwhennostylesareexplicitlysetinthe applicationcode(comparepage41).
List

Fig.4:2columnsinsteadofa normallist.

Alistusesthedynamicselectorlistandalwayscontainschoiceitems.Theselectoroftheseitems dependsonthetypeofthelist.Animplicitlistcontainsalistitem,amultiplelistcontainsa checkboxandanexclusivelistcontainsaradiobox.


list { background-color: pink; }

definesthebackgroundcolorforscreensofthetypeList.
listitem { /* you could also use list listitem */ font-style: bold; }

definesthefontstylefortheitemsinanimplicitlist.
Form

AformusesthedynamicselectorformandcancontaindifferentGUIitems.
form { background-color: pink; }

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

definesthefontstylefornormaltextitemsinaForm.
TextBox

ATextBoxusesthedynamicselectortextboxandcontainsasingletextfielditem.
Example

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

59

TheJ2MEPolishGUIforDesigners
} menu { margin-left: 2; padding: 2; background { type: round-rect; color: white; border-width: 2; border-color: yellow; } focused-style: .menuFocused; menubar-color: transparent; menufont-color: white; } menuItem { margin-top: 2; padding: 2; padding-left: 5; font { color: black; size: medium; style: bold; } layout: left; } .menuFocused extends .menuItem { background-color: black; font-color: white; layout: left | horizontal-expand; after: url(heart.png); } title { 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;

60

TheJ2MEPolishGUIforDesigners
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; 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; }

TheStringItem:Text,HyperlinkorButton Textshavenospecificattributes,butthepaddingverticalattributehasaspecialmeaning: Attribute paddingvertical Required No Explanation Thespacebetweenthelineswhentherethetextcontainsline breaks.

61

TheJ2MEPolishGUIforDesigners Dependingontheappearancemode6ofthetext,eitherthep,theaorthebuttonselectoris usedfordynamicstyles: DynamicSelector p a button Explanation Thepselectorisusedfornormaltexts. Theaselectorisusedforhyperlinks. Thebuttonselectorisusedforbuttons.

Seethegeneralexplanationofdynamicstylesonpage41formoredetails. TheIconItem Iconscanonlybeuseddirectly.Iconssupportfollowingadditionalattributes: Attribute iconimage Required No Explanation TheURLoftheimage,e.g.icon-image: url(icon.png);. Thekeyword%INDEX%canbeusedforaddingtheposition oftheicontothename,e.g. icon-image: url(icon%INDEX%.png);.Theimageusedfor thefirsticonwillbeicon0.png,thesecondiconwillusethe imageicon1.pngandsoon. Thepositionoftheimagerelativetothetext.Eithertop, bottom,leftorright.Defaultstoleft,meaningthatthe imagewillbedrawnleftofthetext.

iconimagealign

No

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

Whentheiconitemhasarightimagealignandthelayoutissettohorizontalexpand,the imagewillbedrawndirectlyattherightborderoftheitem(withagapspecifiedbythepadding rightattribute).Otherwisetheimagewillbedrawnrightofthetextwiththespecifiedhorizontal padding. TheChoiceItem TheChoiceItemisusedinlistsandinchoicegroups.Itsupportsfollowingadditionalattributes:

6 TheappearancemodecanbesetintheapplicationcodewithItem.setAppearanceMode(int).

62

TheJ2MEPolishGUIforDesigners Attribute iconimage Required No Explanation TheURLoftheimage,e.g.icon-image: url(icon.png);. Thekeyword%INDEX%canbeusedforaddingtheposition oftheitemtothename,e.g. icon-image: url(icon%INDEX%.png);.Theimageusedfor thefirstitemwillbeicon0.png,theseconditemwillusethe imageicon1.pngandsoon. Thepositionoftheimagerelativetothetext.Eithertop, bottom,leftorright.Defaultstoleft,meaningthatthe imagewillbedrawnleftofthetext. Thecolorinwhichthecheckorradioboxwillbepainted. Defaultstoblack. TheURLoftheimageforaselecteditem.Thiswillbeused onlywhenthetypeofthelistorofthechoicegroupiseither exclusiveormultiple.Defaultisasimpleimagedrawninthe definedchoicecolor. TheURLoftheimageforanotselecteditem.Thiswillbe usedonlywhenthetypeofthelistorofthechoicegroupis eitherexclusiveormultiple.Defaultisasimpleimagedrawnin thedefinedchoicecolor.Whennoneisgiven,noimagewill bedrawnfornotselecteditems.Onlytheimageforselected itemswillbedrawninthatcase.

iconimagealign

No

choicecolor checkboxselected radioboxselected

No No

checkboxplain radioboxplain

No

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

TheChoiceGroup Achoicegroupcontainsseveralchoiceitems.Itsupportsthefocusedstyleattribute: Attribute focusedstyle Required No Explanation Thenameofthestyleforthecurrentlyfocuseditem.

63

TheJ2MEPolishGUIforDesigners Attribute columns columnswidth Required No No Explanation Thenumberofcolumns.Thiscanbeusedtolayouttheitemsin atable.Defaultsto1column. Eithernormal,equalorthewidthforeachcolumnina commaseparatedlist(e.g.columns-width: 60,60,100;). Defaultstonormal,meaningthateachcolumnusesasmuch spaceasthewidestitemofthatcolumnneeds. Theequalwidthleadstocolumnswhichhaveallthesame width. Theexplicitlistofcolumnwidthsresultsintheusageofthose widths. TheGauge AGaugeshowsaprogressindicator.Itsupportsfollowingadditionalattributes: Attribute gaugeimage Required No Explanation TheURLoftheimage,e.g.gauge-image: url (progress.png);.Whennogaugewidthisdefined,the widthofthisimagewillbeusedinstead. Thecoloroftheprogressbar.Defaultstoblue. Thewidthofthegaugeelementinpixels.Whennowidthis defined,eithertheavailablewidthorthewidthoftheprovided imagewillbeused. Theheightofthegaugeelementinpixels.Defaultsto10. Whenanimageisprovided,theheightoftheimagewillbe used. Eitherchunkedorcontinuous.Inthecontinuousmode onlythegaugecolorwillbeused,whereasthechunkedmode intersectstheindicatorinchunks.Thesettingisignoredwhen animageisprovided.Defaultvalueischunked. Thecolorofgapsbetweensinglechunks.Onlyusedinthe chunkedgaugemodeorwhenagaugewithanindefinite rangeisused.Inthelattercasetheprovidedcolorwillbeused toindicatetheidlestate.Defaultgapcoloriswhite. Thewidthofgapsinpixelsbetweensinglechunks.Onlyused inthechunkedgaugemode.Defaultsto3. Thewidthofthesinglechunksinthechunkedgaugemode.

gaugecolor gaugewidth

No No

gaugeheight

No

gaugemode

No

gaugegapcolor

No

gaugegapwidth gaugechunkwidth

No No

64

TheJ2MEPolishGUIforDesigners Attribute gaugeshowvalue Required No Explanation Eithertrueorfalse.Determineswhetherthecurrentvalue shouldbeshown.Thisdefaultstotrueforalldefinitegauge items. Eitherleftorright.Defineswherethecurrentvalueofthe gaugeshouldbedisplayed.Defaultstoleft,thatisleftofthe actualgaugeitem.

gaugevaluealign

No

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.Currentlytheinputisdonewiththeuseofthenative functions,sothatspecialinputmodescanbeused(likeT9).TheTextFieldsupportsfollowing additionalattributes: Attribute textfieldwidth textfieldheight Required No No Explanation Theminimumwidthofthetextfieldelementinpixels. Theminimumheightofthetextfieldelementinpixels. Defaultstotheheightoftheusedfont.

ThefollowingexampleshowstheuseoftheTextFieldattributes:
.inputStyle { padding: 2; background-color: white; border-color: black; textfield-height: 15; textfield-width: 40; }

65

TheJ2MEPolishGUIforDesigners TheDateField ADateFieldisusedtoenterdateortimeinformation.Currentlytheinputisdonewiththeuseofthe nativefunctions,sothatspecialinputmodescanbeused(likeT9).TheDateFieldsupports followingadditionalattributes: Attribute datefieldwidth datefieldheight Required No No Explanation Theminimumwidthofthetextfieldelementinpixels. Theminimumheightofthetextfieldelementinpixels. Defaultstotheheightoftheusedfont.

Theappearanceofthedatefieldcanalsobeadjustedusingthepreprocessingvariable polish.DateFormat,whichcanbedefinedinthe<variables>sectionoftheJ2MEPolishtask:

<variable name=polish.DateFormat value=us /> :TheUSstandardofMMDDYYYY

isused,e.g.12242004.

<variable name=polish.DateFormat value=de /> :TheGermanstandardof

DD.MM.YYYYisused,e.g.24.12.2004.

Allothersettings:TheISO8601standardofYYYYMMDDisused,e.g.20041224.

66

Appendix

Appendix
IntroductiontoAnt Tobedone. Licenses J2MEPolishislicensedundertheGNUGeneralPublicLicense(GPL)aswellasseveral commerciallicenses. GNUGPL YoucanusetheGPLlicenseforprojects,whicharelicensedundertheGNUGeneralPublic Licensewithoutlimitations. 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.

67

Contact

Contact

ENOUGH SOFTWARE Robert Virkus Vor dem Steintor 218 28203 Bremen Germany Telephone Fax Mobile E-Mail Web +49 (0)421 98 89 131 +49 (0)421 98 89 132 +49 (0)160 77 88 203 Robert.Virkus@enough.de www.enough.de

68

You might also like