Thursday, November 01, 2007

Centering an AIR application window on startup

Ah. Centered window. Mmmmmmm....

This was a bit tricky. I'll take you through it in several steps. Please note that I am running Flex Builder 3 (whatever build was available from labs.adobe.com on 10/30/07), so if you are using a later build Adobe may have fixed this "feature".

Step 1: Referencing the user's screen resolution


You'll need to include a little sum'm sum'm:
import flash.system.Capabilities;


This will allow you to reference the user's native screen dimensions, thus:
Capabilities.screenResolutionX
Capabilities.screenResolutionY

Step 2: Referencing the application's screen position


For this we use the NativeWindow class. For detailed info, see the Flex 3 documentation.
stage.nativeWindow.x
stage.nativeWindow.y

Step 3: Creation (ostensibly) complete


Here's where the real trick is. If you're like me and you wanted to have this "centering" deal happen when the app starts, you probably thought, "I'll just put it in a creationComplete handler and everything will swim." Then you probably got this error:

Cannot access a property or method of a null object reference.

I hit my head against the AS3 wall for a while and brandished my googling skills for a while before I came across Raghu's blog that explained all about why this error crops up. I'll let you read his words for full explanation and just put the fix here.

You need an include:
import mx.managers.SystemManager

You also need to use systemManager in your reference to the stage:
systemManager.stage.nativeWindow.x = ...

So the final code in your creationComplete handler might look like this:
systemManager.stage.nativeWindow.x = Capabilities.screenResolutionX/2-(yourApplicationWidth/2);
systemManager.stage.nativeWindow.y = Capabilities.screenResolutionY/2-(yourApplicationHeight/2);


Hope that makes sense and works for you.

3 Comments:

Blogger Unknown said...

How is using "systemManager.stage.nativeWindow.x" different from using "stage.nativeWindow.x" or using "Capabilities.screenResolutionX" to using "flash.display.Screen.mainScreen.bounds.width"???

They all work the same in my case. I'm on Mac using Flex Builder 3. The tough problem I'm having is that height of the window is wrong in all those cases!?! I guess thats a bug probably ...

4:40 PM  
Blogger Unknown said...

how can we achieve this flash cs3,? it ways systemManager is not defined, though i imported the class

5:24 AM  
Blogger flexdeveloper.in said...

Flex Developer in India- Are you looking for cheap and best quality flex developer, flex application development from India? Get the best designer and developer at flexdeveloper.in. You can call us or mail us at any time in 24*7 formats.

7:32 PM  

Post a Comment

<< Home