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.