In flex, enable property doesn't work for image and radio button etc..here is the sample code for enable and disable the image events....
in the below code the image automatically disabled due to application complete...
once u click the button the image enabled and the event also occur....
//remove the click listener from image
myImg.alpha=0.2;
myImg.removeEventListener(MouseEvent.CLICK, btnClickHandle);
}
private function enableImages():void{
//remove the click listener from image
myImg.alpha=1;
myImg.addEventListener(MouseEvent.CLICK,btnClickHandle);
}
public function btnClickHandle(e:MouseEvent):void
{
Alert.show("enable");
hi,
Object handler is the best way for image handling..inside that you can rotate,resize and flipping the image without any problem..here i am writing simple code for object handle using flex 3.i hope it will help for somebody...
Below example , i did vertical flip, rotation and resizing the image using object handles ...
and u can write function for resizing or used resize handle..
code:
?xml version="1.0" encoding="utf-8"?>
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" xmlns:oh="com.roguedevelopment.objecthandles.*">
protected var resize_handle:Class;
[Embed(source="rotate_handle.png")]
protected var rotate_handle:Class;
public function flip(evt:MouseEvent):void
{
var skewMatrix:Matrix =evt.currentTarget.transform.matrix;
if(skewMatrix.a==1)
{
skewMatrix.a=-1;
skewMatrix.tx=evt.currentTarget.x+evt.currentTarget.width;
evt.currentTarget.transform.matrix = skewMatrix;
}
else{
skewMatrix.a=1;
skewMatrix.tx=evt.currentTarget.x-evt.currentTarget.width;
evt.currentTarget.transform.matrix = skewMatrix;
} } ]]>/mx:Script
here i m writing code for create dynamic repeater in as3...
in my code i try to show the images in vbox through the repeater...
in mxml application we directly give data provider and source to the image.. but in as ae should use loop for increment the data provider, otherwise we get first record of the repeater, it wont repeat the all the records....
To create a simple website in Flex. In this tutorial we will learn to create a four page website.
Step 1: Make New Project :
Create a new project in flex from menu File-->New.
Give name of project website or whatever you want.
Choose application type as web application.
Change the location of project if you want to save it other than default location.
Click finish.
Step 2: Create workspace :
Create a folder images inside src folder by right clicking on src folder and selecting New->Folder.
Open the askmeflash.mxml.
Switch to design mode by clicking design button if already not selected .
Step 3: Create states
Open STATES pannel Right click on base state which is already there.
Select New State. New state window appears . Enter the name and press ok .
Similarly create 3 more states and name them accourdingly.
Step4: Create base template :
To create Header of website .Select the base state and place the image component and give source as logoimage. In this case we have placed askmeflash.com logo.
Below logo we want to display our flex website page links. So we placed an Hbox below logo and placed link buttons inside it. Change the labels of buttons to page names in our case its Articles,Contact,Questions,Tutorials.
In footer we have placed a Hbox and placed Text inside to display copyright information of our Flex Website.
Step5: Add content to pages or states
To add content to articles page . Select the articles state.
Add canvas container to the empty area below links.
Now we can add any design elements like Label ,Image Text etc to canvas component.
Similarly select each state and add content to it .
Step6: Link buttons to states
Select articles button and Switch to source view by clicking Source button
Now add the click event to link button tag and set click="currentState='articles'"
Here articles is state name . Now do this for all the buttons .
when u use crossdomain.xml fill while usimg flash and flex domain.. you have possibility to face security error in flex side...on that time use the following code in ur init() method....
you are using flex and you dont know how to reduce the size of the swf file?..here is the solution for that problem ..
Using RSL in your Project - Runtime Shared Libraries:- Its a flex framework library which contains files required during runtime of flex application. The advantage of RSL is that it’s downloaded once only. RSL simply reduces the file size by approximately 500kb. Implementing RSL is very easy :
GOTO Project -> Properties -> Flex Build Path -> Library Path and select "Runtime Shared Library (RSL)" from the "Framework linkage" combobox.
Press OK and you are done. Now application compiles and creates a framework (swz) file along with swf file looks like framework_3.2.0.3958.swz.
Now you must copy this file to your webserver along with your swf file from where it can be downloaded.
One most important thing is that you must have swz file extension added to your webserver. So that it can be accessed using url. Check that by using your website paths to framework if it can be saved to your disk then its fine else get it fixed first from you web administrator.
RSL is not a only solution for reduce the size , lot of ways available for further details read the links...
1) Make sure AMFPHP 1.9 Beta 1 is in the root of your installation of the amfphp module. The path to it should be: your_drupal_install/modules/amfphp/amfphp
2) Confirm AMFPHP is working. To do this go to administer->site building->services and click on the AMFPHP - /services/amfphp link. If it's working properly you should see something like this:
amfphp and this gateway are installed correctly. You may now connect to this gateway from Flash.
Note: If you're reading an old tutorial, it will tell you that you should see a download window instead of this message. This confused people so this is the new behaviour starting from amfphp 1.2.
View the amfphp documentation
If you get an error make sure you have the correct beta I noted above.
3) Once you've confirmed it's working, create a new Flex project of type "Basic". I called mine AMFPHPTest.
4) Now create a new file anywhere in your project and call it services-config.xml. I created a folder in my project called "services" and put it in there.
5) In this file, you'll want the following. You will need to change the endpoint uri to reflect the location of your own install of the amfphp module:
6) Now add a compiler directive for the services-config.xml file you just created. To do this, do the following:
Right click on your project in Flex Builder and select "Properties".
In the Properties dialog, click on "Flex Compiler".
In the "Additional compiler arguments" textfield, you need to add an additional directive telling Flex the location of your services-config.xml file and its location on your machine. In my case this file is in my default Flex Project location, and my directive looks like the block below. What I added starts with "-services":
Note that in my case it was necessary to provide the full path to the file. This may not be necessary in your case.
Click OK in the Properties dialog.
If you get errors in Flex stating that the services-config.xml file can't be found, then the path to it is wrong. If it is wrong, an error will show up immediately in the "Problems" pane of Flex Builder. If you do not get errors, then your services-config.xml file is being compiled into your project when you click debug or run.
6) In the Application mxml file for your Flex Project, you're going to want something like this:
public function resultHandler(event:ResultEvent):void { // Do something resObject = event.result; result_text.text = "Success! The title of your node is: " + event.result.title; }
public function faultHandler (event:FaultEvent):void { // Deal with event.faultstring, etc. result_text.text = "fault: " + event.fault.toString(); } ]]>
Here's a quick piece-by-piece of the really important bits:
Declare the RemoteObject and method with which we will connect to the node service. That looks like this:
The ID is local to the flex project, specific to the RemoteObject, and is not associated with our services-config.xml
The Source is the node service
The destination matches the destination ID of the service we declared in services-config.xml
The method name is the method of the node service we want to call
The rest should be relatively self-explanatory
Import the classes / packages we need. That looks like this:
Declare the button used to invoke the call to the service. That looks like this:
The click event uses the ID we gave our RemoteObject to first get the specific operation (method) we want to call and then send the request with a NID of 1. In my case this is a Drupal page with a title of "TestPage". You can change the NID to any node you have published.
This article’s introduction section may not adequately summarize its contents. To comply with Wikipedia’s lead section guidelines, please consider expanding the lead to provide an accessible overview of the article’s key points. This article does not cite any references or sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. In computing, a JAR file (or Java ARchive) aggregates many files into one. Software developers generally use .jar files to distribute Java classes and associated metadata. Overview JAR files build on the ZIP file format. Computer users can create or extract JAR files using the jar command that comes with the JDK. They can also use zip tools. A JAR file has an optional manifest file located in the path META-INF/MANIFEST.MF. The entries in the manifest file determine how one can use the JAR file. JAR files intended to be executed as standalone programs will have one of their classes specified as the “main” class. The manifest file would have an entry such as Main-Class: myPrograms.MyClass Users can typically start such JAR files with a command similar to: java -jar foo.jar These files can also include a Classpath entry, which identifies other JAR files for loading with the JAR. This entry consists of a list of absolute or relative paths to other JAR files. Although intended to simplify JAR use, in practice it turns out to be notoriously brittle, as it depends on all the relevant JARs being in the exact locations specified when the entry-point JAR was built. To change versions or locations of libraries, a new manifest is needed. Developers can digitally sign JAR files. In that case, the signature information becomes part of the manifest file. The JAR itself is not signed, but instead every file inside the archive is listed along with its checksum; it is these checksums that are signed. Multiple entities may sign the JAR file, changing the JAR file itself with each signing, although the signed files themselves remain valid. When the Java runtime loads signed JAR files, it can validate the signatures and refuse to load classes that do not match the signature. It can also support ’sealed’ packages, in which the Classloader will only permit Java classes to be loaded into the same package if they are all signed by the same entities. This prevents malicious code from being inserted into an existing package, and so gaining access to package-scoped classes and data.Developers can obfuscate JAR files so that a user of the JAR file doesn’t get much information regarding the code it contains, or to reduce its size, which is useful in mobile phone applications.Microsoft Windows users who prefer having Windows EXE files can use tools such as JSmooth, Launch4J, WinRun4J or NSIS – Java Launcher with automatic JRE installation to wrap JAR files into executables. Eclipse uses a small EXE launcher (eclipse.exe) to display the splash screen on startup and launch the application from the main JAR (startup.jar). Apache Ant Zip/JAR support The Apache Ant build tool has its own package to read and write Zip and JAR archives, including support for the Unix filesystem extensions. The org.apache.tools.zip packageis released under the Apache Software Foundation license and is designed to be usable outside Ant. This code is fast, widely used, and creates most JAR files that are not created with Sun’s utility. [citation needed] Problems with the JAR format The Ant team found that most of their support calls related to JAR file creation have two underlying causes.[citation needed]The first relates to manifest creation, specifically how long lines in the manifest are wrapped. This is a complex and somewhat ambiguous part of the specification. Ant wraps long lines at 68 characters and continues on the following line with a space at the front to indicate a continuation. This is viewed as erroneous by people who have not read the specification in detail and believe that the Classpath should be split at a file boundary, instead of partly across a file name. Unfortunately, if that is done, the Java runtime does not detect a split line as the first line ends before the 68 character boundary. The second is WinZip converting how file and directory names are viewed so that all uppercase names do not appear as such. When set with the default configuration older versions of WinZip (11.1 and earlier) will display all upper case names with only the first letter being uppercase (i.e. Manifest/Manifest.mf). The configuration option “Allow all uppercase filenames” can be checked in the View tab of the Configuration dialog in these versions to remedy the situation. WinZip versions later than 11.1 have this option checked by default. Some mobile phone Java runtimes appear to parse the manifest in ways that are,incompatible with the specification, and require a strict ordering of entries in the manifest. They also do not implement the line wrapping algorithm correctly. This may imply a problem in the test-suite for the Java ME mobile Java runtime.Related formats Several related file formats build on the JAR format: WAR (Web Application aRchive) files, also Java archives, store XML files, Java classes, JavaServer Pages and other objects for Web Applications. RAR (Resource Adapter aRchive) files (not to be confused with the RAR file format), also Java archives, store XML files, Java classes and other objects for J2EE Connector Architecture (JCA) applications. EAR (Enterprise ARchive) files provide composite Java archives which combine XML files, Java classes and other objects including JAR, WAR and RAR Java archive files for Enterprise Applications. See also WAR (file format) EAR (file format) Classpath JAR hell Open Packaging Convention References External links JAR File Specification Using JAR files: The Basics (from Sun) Lesson: Packaging Programs in JAR Files (from Sun) Jar File Overview (from Sun) Jar Class Loader (dynamically loading classes directly from Jar files) fastjar – alternative .jar creation program written in C v • d • eArchive formats (comparison by type) Archiving only ar · cpio · shar · tar · LBR Compression only bzip2 · gzip · LZMA · SQ · compress Archiving and compression 7z · ACE · ARC · Cabinet · cpt · DGCA · .dmg · GCA · kgb · LHA · LZX · RAR · qda · sit · SQX · zoo · ZIP Software packaging and distribution deb · pkg · RPM · RUNZ · MSI · JAR (WAR · RAR (Java) · EAR) Document packaging and distribution OEB Package Format · OEBPS Container Format · Open Packaging Conventions v • d • eData compression software implementations Video compression (Comparison) MPEG-4 ASP 3ivx · DivX · Nero Digital · FFmpeg MPEG-4 · HDX4 · Xvid H.264/MPEG-4 AVC CoreAVC · Blu-code · DivX H.264 · Nero Digital AVC · QuickTime H.264 · x264 Lossless CorePNG · FFV1 · Huffyuv · Lagarith · MSU Lossless · SheerVideo Others CineForm · DNxHD · Helix DNA Producer · Indeo · libavcodec · Schrödinger (Dirac) · SBC · Sorenson · VP7 · libtheora · Windows Media Encoder Audio compression (Comparison) Lossy Freeware Advanced Audio Coding (FAAC) · Helix DNA Producer · l3enc · LAME · TooLAME · libavcodec · Musepack · libvorbis · Windows Media Encoder Lossless FLAC · ALAC · Monkey’s Audio · OptimFROG · TTA · WavPack Archivers (Comparison) Free software 7-Zip · Ark · bzip2 · compress · File Roller · gzip · Info-ZIP · KGB Archiver · lzop · PAQ · PeaZip · The Unarchiver · tar · Xarchiver Freeware 7zX · DGCA · Filzip · IZArc · LHA · StuffIt Expander · TUGZip · UHarc/WinUHA · Zipeg · ZipGenius Proprietary ARC · ALZip · Archive Utility · ARJ · JAR · MacBinary · PKZIP/SecureZIP · PowerArchiver · Squeez · StuffIt · WinAce · WinRAR · WinZip Command line ARC · ARJ · JAR · Info-ZIP · LHA · lzop · PAQ · PKZIP · RAR · UPX · UHarc · tar See Compression Methods for methods and Compression Formats and Standards for formats Retrieved from “http://en.wikipedia.org/wiki/JAR_(file_format)” Categories: Archive formats Java platform Hidden categories: Cleanup from May 2009 All pages needing cleanup Articles lacking sources from June 2008 All articles lacking sources All articles with unsourced statements Articles with unsourced statements from March 2008 Articles with unsourced statements from June 2008 External Links: JAR File Specification Using JAR files: The Basics (from Sun) Lesson: Packaging Programs in JAR Files (from Sun) Jar File Overview (from Sun) Jar Class Loader (dynamically loading classes directly from Jar files) fastjar – alternative .jar creation program written in C [hide] v • d • e Archive formats (comparison by type)
There was a time when I would hold a Nokia in my hand and browse through the menu to play the latest J2ME game. Prince of Persia, Splinter Cell and Zuma were some of my favorites. And then came a time when I started developing on the Flash Lite platform. Whenever I hold a Nokia now, it is always to play a Flash game. Today Flash can compete with the best of technologies to provide an equally challenging game-play experience to users. Adobe is already breaking new ground by launching the Flash Lite Player on a wide range of handheld devices and platforms. Flash Lite is currently available on many phone platforms such as the S60 platform, the S40 platform, Symbian OS, BREW, UIQ, Windows Mobile and the Palm OS. J2ME is also supported on mobile devices worldwide by almost all mobile device manufacturers, and across all air networking standards. This makes it one of the most common platforms that game developers use. However, the game development process using J2ME can be quite complex because the technology was designed for constrained devices. Most content development companies choose to port the games they've developed in order to increase the number of devices and regions where they can make the game available. However the purpose of this article is to share the knowledge of how ports are carried out across different technologies, i.e. from J2ME to Flash Lite. In this article we will assume that the game being ported from J2ME to Flash Lite runs on a S60 handset. Things to consider when porting J2ME games Porting an existing game means you're already halfway there The game development process always begins with a concept stage. Ideally, the pre-production stage for an immersive game should last at least one month. This includes defining the main concepts, debating with the development team on the possibilities of execution, analyzing market feedback on the feasibility of success and finally completing the game design document for the development team. But the process never ends there. Until the game is launched, debates continue and changes are always taking place. However, when you think of porting a game, you are skipping the pre- production stage. You have a team who have "been there and done that"—as a game porter, your main job is define the steps needed and get into action. Save yourself from graphic design limitations Developing a new game often puts designers in an "Artist Block" mode. This is not uncommon in a creative field because creating compelling game visuals is not a simple task. Additionally, designing for a mobile phone with J2ME has its own share of limitations. The graphic designers have to adhere to certain rules, such as: Avoiding anti-alias, because creating the smooth effect uses too many colors. Restricting the number of colors, since the main purpose of pixel art involves creating acceptable images with the least possible colors. Using a limited tool set in an image editing program. This constrains an artist to tools like the pencil tool, bucket tool, selection tools and color replacement tools. Generally artists avoid using gradients, drop shadows and special brush effects in game design. Creating graphics with vectors, rather than drawing freehand. Hand drawn images contain a lot of uneven lines and extra pixels. A pixel designer should strive to create very clean graphics, removing all unnecessary information (see Figure 1).
Figure 1. Graphics for games should be designed with a clean look to avoid unneeded pixels and color variations As you port the game to Flash from J2ME, you can choose to either use the existing bitmap graphics (if they look clean) or recreate the graphics as vectors in Flash. Fortunately, when graphics are recreated in Flash you are not restricted to using limited tools or limited colors. The only caveat is to be careful when dealing with curved edged vectors. This is especially true when designing small graphic elements—try to use as many straight lines as possible (see Figure 2). Figure 2. Use as many straight lines as possible when designing small game graphics Here's another example: We created a round cursor graphic that was 12px x 12px for our ported Flash game. Whenever we tested the game on the device, one side of the round cursor always looked a bit flat. To remedy this, we created a polygon of multiple sides instead of using a circle. When we tested the game again on the device, we had a perfect looking circle, when in reality it was a polygon! Think of it this way: If the bitmap graphics of a J2ME game display clearly, you can use the existing bitmaps in your ported version; otherwise redesign the graphics in Flash as vectors. Use classes to help simplify the porting process and separate the code I think one of the most important considerations to ensure an easy port of a Java game to Flash Lite involves separating the game logic from the user interface code. Ideally, a game developed in any language should have its own classes to handle the game logic, key controls and change in state of the game. Other game features, (such as interface design and persistent data), should be handled by their own classes. The greatest advantage to adopting this method is that the J2ME developer can track the exact game engine code and variables, making the conversion task for the Flash Lite developer much easier. Also, since the J2ME and Flash Lite OOP basic syntax is similar, the conversion of the game logic does not require many corrections. The sample code below was copied from one of our porting projects that involved porting a J2ME game to a Flash Lite game. The code explicitly shows how the game engine code for J2ME is similar to that of Flash Lite. The first example is a simple declaration of variables in J2ME (see Figure 3). Figure 3. Declaring the variables in the J2ME game The second code example shows a similar declaration of variables in our ported Flash Lite version of the game (see Figure 4). Figure 4. Declaring the variables in the Flash Lite version of the game If you compare the two code snippets above, you will notice that the variable declaration is very similar in J2ME and Flash Lite. In fact, the code in Flash has been altered and optimized to make it more adaptable for Flash on mobile devices. For instance, in the J2ME code example each game mode has been declared as a separate variable, (such as MODE_NORMAL, MODE_TIMED and MODE_SURVIVAL). In contrast, the Flash Lite code declares a single variable, (gMode) which dynamically stores a value, depending upon which mode the user chooses to play in at run-time. Testing 1-2-3 Although the original game was tested thoroughly, your ported game requires a testing phase too. It is critical that game developers identify and eliminate bugs before distribution, in order to provide expected game play on all platforms. Flash Lite porters have a huge advantage here, because they already have the bug list of the game from the J2ME development phase. As a Flash Developer responsible for porting the game, you simply need to run through your game file and check to see if you are repeating any errors from the bug list. This step is very important and highly recommended. Checking for repeated errors will considerably help reduce the bugs in your ported game. Supporting multiple devices in Flash Lite and J2ME The biggest advantage Flash Lite has over J2ME is that a single compiled swf file can be supported on multiple devices. In theory that is true, but it is important to note that in real-world examples, the content may need to be redesigned to fit the mobile device. User experience can be affected if content that was designed for larger screens is scaled to display on a phone. The S60 mobile devices come with different screen sizes. The list below shows the most common dimensions: 176 X 208 240 X 320 352 X 416 320 X 240 A common practice in game development is to start building on a base device, usually using a screen resolution of 176px x 208px. Once the content is completely ready, (after the testing phase and bug fixes are completed), the game content is sent to the porting team to port it for multiple devices. The process of porting in J2ME is different from the porting for Flash Lite. In J2ME games, developers often hard code every value. The values for moving a sprite, for placing a sprite on a canvas, for setting up a tiled background and for setting up fonts on the canvas during run-time are usually all hard coded. That means that in order to port a J2ME game to a bigger screen size, the hard coded values must be updated. Also, since the graphics in J2ME games are bitmaps, the graphics will need to be redesigned at a larger size and enhanced for a higher resolution screen size (see Figure 5). Figure 5. Bitmap game graphics ported to a larger screen size must be re- created to display correctly As a game developer ports a J2ME game, they must also change the API. In these situations, the code itself must also be changed. It is much easier to port a Flash Lite game across multiple devices, because you have complete control over the UI and the inside game elements. You can manipulate graphics and fonts during author-time. Additionally, since the graphics are already vectors, the elements only require resizing and do not need to be recreated to display on different screen sizes (see Figure 6). Figure 6. Vector graphics have an advantage because they can be resized to fit various screen sizes Flash runs uniformly on all platforms, because it does not depend upon the platform API. This is definitely a huge time saver because it is not necessary to change your code unless you have hard coded the game values when developing. Similarities in Porting Flash Lite 2.0 and MIDP 2.0 Flash Lite and J2ME are similar in many areas, and it is these similarities that make the process of porting between the two platforms much easier. Here is a list of the characteristics both platforms have in common: Both the technologies are based on the Symbian OS. This means a J2ME game and a Flash Lite game both run on top of the device UI layer. Just as J2ME has external APIs to access the device functionalities, Flash Lite has its FSCommand functions to communicate with the device. Most Series 60 devices have a screen size of 176 X 208. J2ME and Flash Lite can maintain this screen size for their game during the port. The screen size issues usually occur only if the game that is being ported has a higher resolution in J2ME compared to Flash Lite. The user interface of every Series 60 device has two soft keys, a five-way rocker, and a numeric keypad. This makes it much easier to map the keys in Flash Lite from J2ME to initiate game actions. Both J2ME and Flash Lite support menus, although in J2ME, a menu structure can be altered, (which is not true in Flash Lite). Pressing the left-hand softkey, (usually named Options), activates a menu on any S60 device. Both technologies use the numeric keypad to enter data in text fields and to navigate through applications. On Series 60 devices, one-hand operation is the key rule. The user is able to do almost all tasks with one hand, by pressing the keys with the thumb. Characters are entered with multiple key presses in both cases. The preferred final compiled file sizes of the game (the .jar and .swf files) of both these technologies should be between 250-300K. A developer can build games that are up to 500K. However, be aware that the game could potentially lose revenue if the end user opts not to wait for the large game to download. The preferred sound implementation on both these technologies is the MIDI format. Flash Lite developers could also use MP3 and WAV sound formats, but MIDI is the sound format of choice because the goal is to decrease file size whenever possible. If the game's file size allows for extra room for improvement, developers tend to use this as an opportunity to add more graphics or code. A J2ME file requires JVM (Java Virtual Machine), also known as a KVM (Kilobyte Virtual Machine) for mobile devices. KVM is a platform optimized for small footprint consumer devices, to execute .jar files. A Flash Lite file requires a Flash Lite Player, a desktop Flash Player profile (based on the Flash 7 engine), installed on the phone to play back the .swf files. Differences in Porting Flash Lite 2.0 and MIDP 2.0 When porting a game from J2ME to Flash Lite, you may also encounter differences between the two technologies, which can add some complications to the process. The differences and issues you may encounter are outlined below. Vector verses raster The biggest difference between the two platforms is the format of graphics supported by both these technologies. While J2ME supports only raster graphics, Flash Lite supports a combination of vectors and rasters. It is recommended that developers recreate the graphics for use in the Flash Lite game before porting. Only raster images from the J2ME version of the game can be used, and although they can look acceptable, the graphics will look clearer if they are recreated as vectors. To illustrate this point, I've included screen shots from two versions of the same game. The J2ME game uses raster graphics, which are legible but look faded and blurry (see Figure 7). Figure 7. A screen shot from a J2ME game Figure 8. A screen shot from a Flash Lite game The Flash Lite version is definitely enhanced when compared to the J2ME version, because the vector graphics look crisp and bright (see Figure 8). Garbage collection and heap memory All Series 60 devices come with a default heap memory of 1.5MB for applications to run smoothly. A Java or Flash developer has to optimize the code to make it device friendly, while keeping this heap memory in mind. One characteristic that makes J2ME a programmer-friendly language is the use of automatic memory allocation and de-allocation. When the programmer instantiates a variable, the JVM finds and allocates the memory without the programmer calling a malloc () or new (). Likewise, the JVM de- allocates that memory when the variable is no longer used, or goes out of scope. The process of reclaiming memory is called garbage collection. In J2ME, a developer can try flushing the memory by using the System.gc () method, but this will only slow down the application performance. Ultimately, it is best for a game developer to let the application handle its own garbage collection. When developing games using Flash Lite, there currently isn't a method which a developer can use to guess how much of the heap memory is being used. Optimizations are done based on experience and assumptions. However, like Java, Flash also has its own garbage collection. According to the Flash Lite documentation, the garbage collection in Flash runs automatically every 60 seconds (or when the memory exceeds 200% of the current memory usage). That all sounds great, but sometimes a Flash application will crash anyway—causing the developer to wonder why. Playback via the Flash Lite Player compared to the JVM A Series 60 device comes embedded with the JVM, (also known as KVM) for smaller footprint devices. When a J2ME game is run on a device, it launches in the JVM and uses its underlying APIs to perform. Conversely, the Flash Lite Player must be installed on the device to play a Flash game. Most of the older Nokia Series 60 Second Edition phones don't support Flash Lite 2.0 (they only support Flash Lite 1.1). The newer Nokia Series 60 Third Edition phones come with the Flash Lite 1.1 player preinstalled, however the latest version of Flash Lite still needs to be installed if it is required. Comparing vectors on the stage to drawing graphics on the canvas When developing in J2ME, the game developer has to deal with drawing sprites or images on a canvas. In the code example below, the screen appears to clear by drawing a rectangle the size of the screen and setting its color to white. Then, two more objects are drawn on screen, (a line and a rectangle): import javax.microedition.lcdui.*; class DrawingDemoCanvas extends Canvas { public void paint (Graphics g) { g.setGrayScale (255); g.fillRect (0, 0, getWidth (), getHeight ()); g.setGrayScale (0); g.drawLine (0, 0, 100, 200); g.fillRect (20, 30, 30, 20); } } Now pretend you are developing the same game in Flash. If you need simple graphics like those used in the code above, you can use the drawing tools in Flash to achieve the same effect during authoring. Using Flash Lite 2.0, you can choose to write code using the Drawing API to achieve this as well. Personally, I feel it is much faster and easier to use the drawing tools, rather than add more lines of code to my script. The drawing tools are a definite advantage to developing games in Flash (see Figure 9). Figure 9. Simple game graphics can be created using the drawing tools in Flash Lite 2.0. When developing in J2ME, the same graphics must be generated programmatically Working with fonts When developing with Flash Lite, it is easy to work with fonts because you have complete control over the design of your content. Text Boxes can be drawn on the stage using the Text tool, and text properties are controlled using the Properties Inspector (see Figure 10). Figure 10. Using Flash Lite, you can control where you place the text and how the text will be displayed It is a common misconception that developers should avoid embedding multiple fonts in a game, in order to keep a small file size. In my experience, when your content can have a file size of 300K, it is feasible to use several good pixel fonts for your content. In contrast to the above, the text in J2ME games must be drawn using the drawstring () method. This method requires you to define four parameters: The character string, the x and y coordinates, and an integer determining the horizontal and vertical alignment of the text. If you are using a canvas based application you can create the necessary graphics using your own customized fonts, then save the text as an image file along with your other graphics images. You could then theoretically use the customized fonts wherever desired in your game. But it is not quite that simple. If you use customized graphics for your text, you will need to know the coordinates of every character of the image file. In the next example, a customized font image is displayed on the left side. The right side shows how the characters are displayed on the device (see Figure 11). Figure 11. The custom font image appears on the left while the right side shows how the device displays the text Here's how this works. The top-left and bottom-right coordinates of every character from the image are fed into the game program. During run-time the game program reads the string, picks the character from the image and then draws it on the canvas. As you can imagine, this is a very tedious process. These days when I think of using custom fonts, I cannot help but smile and be thankful that I'm using Flash Lite as a mobile development tool. Where to go from here In this article I've covered some techniques and considerations for porting J2ME games to the Flash Lite platform. In my personal experience, porting projects always begins by thoroughly reading the Game Design Document. Once I have a complete understanding of the game logic from the previous J2ME development team, I start collecting the useful code snippets (such as conditions, the game AI, etc.), and begin translating the game into ActionScript (using the Flash syntax). A Flash Lite developer porting a game from J2ME to Flash Lite has some advantages that will make their job easier. The first advantage is that the game assets are already available. Additionally, a Flash Lite developer does not have to spend too much time working on the game logic or designing compelling game visuals. When it comes to porting an existing game, the entire content has already been created. It is a simple matter to reproduce and test the ported game before distributing it. Expand your knowledge about S60 development by reading the detailed information on the Nokia S60 documentation forum. Also, in-depth articles and tutorials about using Flash Lite are available at the Adobe Mobile & Devices Developer Center. I hope this article has sparked your interest in porting game content. Although porting is easier than developing a brand new game, you'll find the process will be easiest if you invest time in learning about the original development, recreate the game graphics as needed, and define your porting strategies ahead of time—especially if you are porting across different technologies. Adobe still working out solution for j2me jar application to be import in flex 3.0. anybody wants to share their ideas regarding flex, They are welcome.
Accessing the Throwable object in Flex RemoteObject component invokes the fault event when an error occurs while remote method invocation. The fault event handler is provided with the FaultEvent object. This FaultEvent object has property named message of type mx.messaging.messages.ErrorMessage. The message property holds the Throwable object from the Java method in the rootCause property. We need to use this rootCause property to retrieve the properties which are set to the Throwable object in Java. All the public properties from the Throwable object are available. We will see a sample application. In this application I am creating a custom Exception and adding a getter method to that, which will return my custom data. From the Flex application I will access both the error message and the custom data. MyException.java public class MyException extends Exception { public MyException(String message) { super(message); } public String getMyName(){ return “Sujit Reddy G”; } }
Method throwing exception This method will throw the custom exception created above, add this method to a Java class. Invoke the below method using RemoteObject component in Flex.
public void throwCheckedException() throws Exception{ throw new MyException(”This is a checked exception”); } Reading values in Flex application We add the method below as the fault event handler to the RemoteObject component in the Flex application. You can see that we accessed the rootCauseobject to retrieve the properties of the custom Exception object returned from the Java method. private function handleException(event:FaultEvent):void{ var errorMessage:ErrorMessage = event.message as ErrorMessage; Alert.show(errorMessage.rootCause.message); Alert.show(errorMessage.rootCause.myName); } We are adding the above method as fault event handler to the RemoteObject component. fault=”handleException(event)”/> Invoking the method in the Java class on button click You can also use the flex.messaging.MessageException. This class is packaged in the flex-messaging-core.jar. You should throw MessagException instead of MyException or any custom exception created. MessageException provides a property named extendedData, which is a HashMap. You can add any data to this property and access it from the Flex application using ErrorMessage(event.message).extendedData.
1.Create a Java Class that extends RuntimeException. package com.flex3.exception; public class FlexException extends RuntimeException{ public FlexException(String message) { super(message); } } 2. Create a matching flex class called FlexException, and put the usual RemoteObject tag in their so BlazeDS will know what to look for. Also remember in actionscript, each object must be instantiated at least once, so be sure to do that somewhere with FlexException. 3. In Java, whenever there is a known exception, or some error where the end user needs to be shown a message, throw a FlexException and pass in the message the user should see in the constructor. Let’s say the user just entered an invalid password. throw new FlexException(”Wrong Password Entered, Please Try Again.”); 4. Flex receives the Exception in the form of a fault. In the fault handler, you call this method:/*** Parse the incoming fault for an FlexException class. If the exception class is found and it has a matching actionscript class,* show an alert to the user with the correspoding messages. If we don’t recognize the Exception type, show a generic error.** @param fault**/public static function handleException(fault:Fault): void{var msg : String = fault.faultString;var clazz : Class = getExceptionClass(fault);var instance : Error = null;if (clazz != null){Alert.show(msg,’Error’);}else{Alert.show(’Error! Please try again. If this issue persists, contact the system administrator’);}}/**** Return the Class corresponding to the exception by parsing the fault string. If a corresponding actionscript error class is found,* return it. Otherwise, return null.** @return**/ public static function getExceptionClass(fault:Fault) : Class{ var clazz:Class = null; var index:int = myFault.faultString.indexOf(”FlexException”); if (index != -1){var cname:String = myFault.faultString.substr(0,index-1); try{ clazz = getDefinitionByName(”com.flexpasta.FlexException”) as Class; } catch (e:ReferenceError){ } } return clazz; } When we see a Flex Exception, we show the message to the end user. If for some reason we have an unplanned error in Java, like NullPointerException, a message is displayed to the end user: ‘Error! Please try again. If this issue persists, contact the system administrator’. A generic message to handle all unplanned errors. 5. What if the app needs to DO something special with certain Java Exceptions? Say the user has just entered 3 password attempts, and I want to be able to handle locking their account through an exception. Create a new class in Java called UserLockedException that extends FlexException Create a matching actionscript UserLockedException. Add code in the flex fault handler to look for a UserLockedException, when the fault handler sees it, it can still display a message to the end user, but now flex knows to take a different code path to complete the process.
Many widgets need to interact with the map. To do this, simply connect the widget with the map in three steps: Override the start method to access OSGi services Create your logic Create your user interface (UI) View a live sample. Step 1: Override the start method to access OSGi services To enable your widget to interact with the map, you need to override the Start method of the Widget Base and create an instance of the Service Tracker which will allow you to directly access the OSGi services. package com.esri.aws.awx.widget { public class MyZoomBaseWidget extends BaseWidget { import com.esri.aws.awx.map.IMap; import com.esri.aws.osgi.framework.IBundleContext; import com.esri.aws.osgi.framework.ServiceTracker; import flash.utils.getQualifiedClassName; // instance of service tracker private var theTracker:ServiceTracker; // Override the start() method override public function start(context:IBundleContext):void { super.start(context); theTracker = new ServiceTracker(context, getQualifiedClassName(IMap)); theTracker.open(); } override public function createWidgetView(widgetState:String = null):IWidgetView { var theCustomView:MyZoomWidgetView = new MyZoomWidgetView(); theCustomView.widget = this; theCustomView.widgetState = widgetState; return theCustomView; } } } Step 2: Create your logic Add a function in widget base that “does something”, for example: public function onZoom(value:Number):void { var map:IMap = IMap(theTracker.getService()); if(map) { map.scale *= value; } } Step 3: Create your UI Create your user interface. Add a Map to your main MXML file: Add the UI: mx:Text text="Widget that interacts with Map" />
In addition to the widgets provided with ArcWeb Explorer (Base Maps, Find, and Pan&Zoom), you can also create your own widgets. You can create your own widgets in ArcWeb Explorer Flex API using these setup instructions. View a live sample. Requirements Adobe Flex 2.01 with or without HotFix 1 (newer hot fixes are not supported)—If you don't have a Flex development environment, you can download a free trial of the Flex Builder IDE. Download the following files: SWC file Widget SWC file Creating widgets To create your own widget, you need to: Implement IWidgetView and create default widget state (visual). Extend BaseWidget (non-visual). Wrap BaseWidget in MXML (wrapping). Step 1: Implementing IWidgetView and creating default widget state (visual) First, create the visual parts of the widget. You need to implement the six functions of the IWidgetView interface, and create the default widget state. MyImplementationOfWidgetView.mxml contains an example:
xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:widget="com.esri.aws.awx.widget.*" implements="com.esri.aws.awx.widget.IWidgetView"> import com.esri.aws.awx.widget.WidgetStates; import com.esri.aws.awx.widget.IWidget; private var theWidget:MyWidget; public function get widget():IWidget { return theWidget; } public function set widget(value:IWidget):void { theWidget = value as MyWidget; } public function set widgetState(value:String):void { currentState = value; } public function get widgetState():String { return currentState; } private var theWidgetContainer:IWidgetContainer; public function get widgetContainer():IWidgetContainer{ return theWidgetContainer; } public function set widgetContainer(container:IWidgetContainer):void{ theWidgetContainer = container; } ]]>
Step 2: Extending BaseWidget (non-visual) Extend the BaseWidget class using the createWidgetView method. The createWidgetView method should return the widget view created above (MyImplementationOfWidgetView). This is usually where your business logic goes (non-visual). MyExtendedBaseWidget.as contains an example: package com.esri.aws.awx.widget { public class MyExtendedBaseWidget extends BaseWidget { override public function createWidgetView(widgetState:String = null):IWidgetView { var theCustomView:MyImplentationOfWidgetView = new MyImplentationOfWidgetView(); theCustomView.widget = this; theCustomView.widgetState = widgetState; return theCustomView; } } } Step 3: Wrapping BaseWidget in MXML The last step is to wrap the extended BaseWidget in MXML. This wrapper contains the metadata associated with the widget and declares the states available within the widget view. It is referenced from the MyImplementationOfWidgetView.mxml. MyFirstWidget.mxml contains an example:
Using widgets in Flex You can easily use the built-in widgets in your own applications with the WidgetPopupManager. Currently there are three built-in widgets: "Find", "Pan & Zoom", and "Base Maps". The sample below illustrates how to use the DockWidgetContainer to add widgets for "Find", "Pan & Zoom", and "Base Maps". See the using a widget sample for details. You can also use the lazy loaded version of these widgets. See the reference documentation on BaseMapWidgetLoader, FindWidgetLoader, and PanZoomWidgetLoader for more information. xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:awx="http://www.arcwebservices.com/2007/awx" xmlns:widget="com.esri.aws.awx.widget.*" layout="absolute">
Widgets in ArcWeb Explorer are easy to use, and re-use modules that provide specific functionality. You can use one of the provided widgets, use someone else’s widget, or create and use your own widgets. For example, you might want to create a widget that provides easy access to your data or services; a widget that’s almost a complete application in its own right; or a widget that creates driving directions to your specific locations. The possibilities are endless. Widgets are based on three important concepts: Widget containers: Widget containers are used to “house” the widgets, for example, FloatingWidgetContainer. The non-UI part of the widget: This contains the business logic for the widget. Widget view: The widget view can contain one or more widget states, for example, DEFAULT, INFO, and ICON. To display widgets, you put them in widget containers. You can either use one of the existing four widget containers, or create your own. The existing widget containers are: AccordionWidgetContainer: AccordionWidgetContainer can be used to group several widgets into one. It supports the DEFAULT widget state. BarWidgetContainer: BarWidgetContainer is a type of "carousel container" that provides the ability to scroll through its content, either horizontally or vertically. It uses the ICON and ICON_ACTION widget states. DockWidgetContainer: DockWidgetContainer is an interactive widget container that can be "docked" to the side of an application. It contains a BarWidgetContainer, and thus uses the ICON and ICON_ACTION widget states. FloatingWidgetContainer: FloatingWidgetContainer is a "popup" widget container that "floats" atop the application. This is the widget container used by the "Base Maps", "Find", and "Pan and Zoom" widgets. Alternatively you could put those widgets in a different widget container. FloatingWidgetContainer uses the DEFAULT, INFO, and ICON widget states. Use the WidgetPopupManager to open (“pop up”) floating widget containers. NOTE: This page does not discuss creating your own widget container (HINT: extend BaseWidgetContainer). If you style your widgets correctly, they will have the same look and feel as the widgets provided in ArcWeb Explorer. Using stylesheets, you can change the look and feel of all widgets (including your own).