Archive for the 'Flex' Category

Support CSS state selector with ID selector for Spark SkinnableContainer

Wednesday, August 18th, 2010

Main.mxml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
< ?xml version="1.0" encoding="utf-8"?>
<s :WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
					   xmlns:s="library://ns.adobe.com/flex/spark" 
					   xmlns:mx="library://ns.adobe.com/flex/mx" 
					   xmlns:local="*"
					   creationComplete="creationCompleteHandler(event)">
	<fx :Style>
		@namespace s "library://ns.adobe.com/flex/spark";
		@namespace mx "library://ns.adobe.com/flex/mx";
		@namespace local "*";
 
		local|MyTestContainer #textDisplay
		{
			color:#0099FF;
		}
 
		local|MyTestContainer:green #textDisplay
		{
			color:#00FF99;
		}
 
		local|MyTestContainer:red #textDisplay
		{
			color:#FF9900;
		}				
	</fx>
 
	<fx :Script>
		< ![CDATA[
			import mx.collections.ArrayCollection;
			import mx.collections.IList;
			import mx.events.FlexEvent;
 
			import spark.events.IndexChangeEvent;
 
			[Bindable]
			private var stateSelectorDataProvider:IList;
 
			protected function stateSelector_changeHandler(event:IndexChangeEvent):void
			{
				myTestContainer.currentState = event.currentTarget.selectedItem.name;
			}
 
 
			protected function creationCompleteHandler(event:FlexEvent):void
			{
				stateSelectorDataProvider = new ArrayCollection(myTestContainer.states);
			}
 
		]]>
	</fx>
	<fx :Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx>
	</s><s :layout>
		<s :VerticalLayout/>
	</s>
 
	<s :DropDownList id="stateSelector" dataProvider="{stateSelectorDataProvider}" 
					change="stateSelector_changeHandler(event)"
					selectedIndex="-1" 
					labelField="name"/>
	<local :MyTestContainer id="myTestContainer" skinClass="MyTestContainerSkin"/>

MyTestContainer.mxml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
< ?xml version="1.0" encoding="utf-8"?>
<components :MySkinnableContainer xmlns:fx="http://ns.adobe.com/mxml/2009" 
													 xmlns:s="library://ns.adobe.com/flex/spark" 
													 xmlns:mx="library://ns.adobe.com/flex/mx" 
													 xmlns:components="com.experiment.framework.components.*" 
													 width="400" height="300"
													 currentState="normal">
	<fx :Metadata>
		[SkinState("normal")]
		[SkinState("green")]
		[SkinState("red")]
	</fx>
	<fx :Declarations>
		<!-- Place non-visual elements (e.g., services, value objects) here -->
	</fx>
	</components><components :states>
		<s :State name="normal"/>
		<s :State name="green"/>
		<s :State name="red"/>
	</components>
	<s :Label id="textDisplay" text="This is Css State Selector Support"/>

MySkinnableTestContainer.as

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.experiment.framework.components
{
	import mx.styles.IStyleClient;
 
	import spark.components.SkinnableContainer;
 
	public class MySkinnableContainer extends SkinnableContainer
	{
		public function MySkinnableContainer()
		{
			super();
		}
 
		override public function setCurrentState(stateName:String, playTransition:Boolean=true):void
		{
			super.setCurrentState(stateName,playTransition);
			invalidateSkinState();
		}
 
		override public function invalidateSkinState():void
		{
			super.invalidateSkinState();
			var styleClient:IStyleClient = this as IStyleClient;
			var styleName:Object;
 
			if(styleClient)
			{
				if(styleClient.styleName == null)
				{
					styleClient.styleName = {};
					styleClient.styleName = null;
				}
				else
				{
					styleName = styleClient.styleName;
					styleClient.styleName = null;
					styleClient.styleName = styleName;
				}
			}
		}
 
		override protected function getCurrentSkinState():String
		{
			return currentState;
		}
 
	}
}

MyTestContainerSkin.mxml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
< ?xml version="1.0" encoding="utf-8"?>
 
<!--
 
    ADOBE SYSTEMS INCORPORATED
    Copyright 2008 Adobe Systems Incorporated
    All Rights Reserved.
 
    NOTICE: Adobe permits you to use, modify, and distribute this file
    in accordance with the terms of the license agreement accompanying it.
 
-->
 
<!--- The default skin class for a Spark SkinnableContainer container.  
 
     @see spark.components.SkinnableContainer
 
      @langversion 3.0
      @playerversion Flash 10
      @playerversion AIR 1.5
      @productversion Flex 4
-->
<s :Skin xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:fb="http://ns.adobe.com/flashbuilder/2009" alpha.disabled="0.5">
 
    <fx :Metadata>
    < ![CDATA[ 
        /** 
         * @copy spark.skins.spark.ApplicationSkin#hostComponent
         */
        [HostComponent("spark.components.SkinnableContainer")]
    ]]>
    </fx> 
 
    </s><s :states>
        <s :State name="normal" />
        <s :State name="disabled" />
		<s :State name="green"/>
		<s :State name="red"/>
    </s>
 
    <!--- Defines the appearance of the SkinnableContainer class's background. -->
    <s :Rect id="background" left="0" right="0" top="0" bottom="0">
        </s><s :fill>
            <!--- @private -->
            <s :SolidColor id="bgFill" color="#FFFFFF"/>
        </s>
 
 
    <!--
        Note: setting the minimum size to 0 here so that changes to the host component's
        size will not be thwarted by this skin part's minimum size.   This is a compromise,
        more about it here: http://bugs.adobe.com/jira/browse/SDK-21143
    -->
    <!--- @copy spark.components.SkinnableContainer#contentGroup -->
    <s :Group id="contentGroup" left="0" right="0" top="0" bottom="0" minWidth="0" minHeight="0">
        </s><s :layout>
            <s :BasicLayout/>
        </s>

Disable a Tab in Spark TabBar

Wednesday, August 18th, 2010

Use the class below as the itemRenderer of the Spark TabBar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import flash.events.Event;
 
import mx.core.INavigatorContent;
 
import spark.components.ButtonBarButton;
 
public class ButtonBarButton extends spark.components.ButtonBarButton
{
	public function ButtonBarButton()
	{
		super();
	}
 
	override public function set data(value:Object):void
	{
		if(data is INavigatorContent)
			INavigatorContent(data).removeEventListener("enabledChanged",enabledChangedHandler);
 
		super.data = value;
 
		if(data is INavigatorContent)
		{
			INavigatorContent(data).addEventListener("enabledChanged",enabledChangedHandler);
		}
	}
 
	private function enabledChangedHandler(event:Event):void
	{
		enabled = INavigatorContent(data).enabled;
	}
}

as3 DateParser

Friday, April 23rd, 2010
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
////////////////////////////////////////////////////////////////////////////////
// DateParser.as
//
// An as3 implementation of the java SimpleDateFormat like class based on Flex 
// SDK which can be used to parse a String with specified format to as3 Date 
// object.
//
// This code is a modification version of Daniel Wabyick's as2 
// SimpleDateFormatter(http://osflash.org/simpledateformatter) which 
// is directly adapted from Matt Kruse's Javascript class implementation.
//
// @author edison.guo(http://www.hydra1983.com)
// @author Daniel Wabyick(http://www.fluid.com)
// @author Matt Kruse (http://www.JavascriptToolbox.com)
 
// The following notice is maintained from Matt Kruse's 
// original Javascript code. 
// 
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// USAGE
// ----------------------------------------------------------------------
// These functions use the same pattern letters used by the DateFormatter 
// class provided by Flex SDK. You can find the detailed description of 
// these letter in the Adobe Flex Language Reference.
// Examples:
//		var dateString:String = "9/10/2008 GMT+0800 08:30:41";
// 		var parser:DateParser = new DateParser();
//		parser.formatString = "M/D/Y HH:NN:SS";
//		trace(parser.parse(dateString));
//		//Wed Sep 10 08:30:41 GMT+0800 2008
//
// ----------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
 
package
{
	import mx.formatters.Formatter;
	import mx.utils.StringUtil;
 
	public class DateParser
	{
		private static const VALID_PATTERN_CHARS:String = "Y,M,D,A,E,H,J,K,L,N,S,Q";
 
		public var error:String;
 
		private var _formatString:String = "YYYY-MM-DD HH:NN";
 
		public function get formatString():String
		{
			return _formatString;
		}
 
		public function set formatString(value:String):void
		{
			if(value) _formatString = value;
		}
 
		private var _defaultInvalidFormatError:String = Formatter.defaultInvalidFormatError;
 
		public function get defaultInvalidFormatError():String
		{
			return _defaultInvalidFormatError;
		}
 
		public function set defaultInvalidFormatError(value:String):void
		{
			_defaultInvalidFormatError = value;
		}
 
		private var _defaultInvalidValueError:String = Formatter.defaultInvalidValueError;
 
		public function get defaultInvalidValueError():String
		{
			return _defaultInvalidValueError;
		}
 
		public function set defaultInvalidValueError(value:String):void
		{
			_defaultInvalidValueError = value;
		}
 
		public function parse( value:Object):Date 
		{
			if (error)
				error = null;
 
			if(!(value is String))
			{
				error = defaultInvalidValueError;
				return null;
			}
 
			if(!value || value == "")
			{
				error = defaultInvalidValueError;
				return null;
			}
 
			var timezoneRegEx:RegExp = /(GMT|UTC)((\+|-)\d\d\d\d(\s)?)?/ig;
			value = StringUtil.trim(String(value).replace(timezoneRegEx, ""));
 
			var letter:String;
			var nTokens:int = 0;
			var tokens:String = "";
 
			var n:int = formatString.length;
			for (var i:int = 0; i < n; i++)
			{
				letter = formatString.charAt(i);
				if (VALID_PATTERN_CHARS.indexOf(letter) != -1 && letter != ",")
				{
					nTokens++;
					if (tokens.indexOf(letter) == -1)
					{
						tokens += letter;
					}
					else
					{
						if (letter != formatString.charAt(Math.max(i - 1, 0)))
						{
							error = defaultInvalidFormatError;
							return null;
						}
					}
				}
			}
 
			if (nTokens < 1)
			{
				error = defaultInvalidFormatError;
				return null;
			}
 
			var dataParser:DateStringParser = new DateStringParser(
				formatString, VALID_PATTERN_CHARS);
 
			return dataParser.parseValue(value);	
		}
	}
}
import mx.formatters.DateBase;
 
class DateStringParser
{
	private static var digits:String = "1234567890";
 
	private static var dayNames:Array = DateBase.dayNamesLong.concat(DateBase.dayNamesShort);
 
	private static var monthNames:Array = DateBase.monthNamesLong.concat(DateBase.monthNamesShort);
 
	public function DateStringParser(format:String, tokens:String)
	{
		super();
 
		this.format = format;
		this.tokens = tokens;
	}
 
	private var format:String;
 
	private var tokens:String;
 
	public function parseValue(value:Object):Date
	{		
		var valueString:String = String(value);
 
		var i_value:int = 0;
		var i_format:int = 0;
		var char_token:String = "";
		var token:String = "";
		var start:int = 0;
		var end:int = 0;
 
		var now:Date = new Date();
		var years:Object = now.getFullYear();
		var months:Object = now.getMonth() + 1;
		var dates:Object = now.getDate();	
		var days:Object = now.getDay();
		var hours:Object = now.getHours();
		var minutes:Object = now.getMinutes();
		var seconds:Object = now.getSeconds();
		var milliseconds:Object = now.getMilliseconds();
		var ampm:String = "";
 
		var max:int = 0;
		var min:int = 0;
 
		while(i_format < format.length)
		{
			char_token = format.charAt(i_format);
			if(tokens.indexOf(char_token) > -1)
			{
				start = format.indexOf(char_token);
				end = format.lastIndexOf(char_token);
				end = end >= 0 ? end + 1 : start + 1;
				token = format.substring(start,end);			
				i_format = end;
 
				if(token == "YYYY" || token == "YY" || token == "Y")
				{					
					if(token == "YYYY") {max = min = 4;}
					if(token == "YY") {max = min = 2;}
					if(token == "Y"){max = 4;min = 2;}
 
					years = getIntegerValue(valueString,i_value,min,max);
					if(isNaN(Number(years))) return null;
					i_value += String(years).length;
					years = Number(years);
				}
				else if(token == "MM" || token == "M")
				{
					months = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(months)) || months < 1 || months > 12) return null;
					i_value += String(months).length;
					months = Number(months);
				}
				else if(token == "MMMM" || token == "MMM")
				{
					var monthName:String = getMonthName(valueString,i_value);
					if(!monthName || monthName.length == 0) return null;
					months = getMonths(monthName);
					if(isNaN(Number(months)) || months < 1 || months > 12) return null;
					i_value += monthName.length;
					months = Number(months);
				}
				else if(token == "EE" || token == "E")
				{
					days = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(days)) || days < 1 || days > 7) return null;
					i_value += String(days).length;
					days = Number(days);
				}
				else if(token == "EEEE" || token == "EEE")
				{
					var dayName:String = getDayName(valueString,i_value);
					if(!dayName || dayName.length == 0) return null;
					days = getDays(dayName);
					if(isNaN(Number(days)) || days < 1 || days > 7) return null;
					i_value += dayName.length;
					days = Number(days);
				}
				else if(token == "DD" || token == "D")
				{
					dates = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(dates)) || dates < 1 || dates > 31) return null;
					i_value += String(dates).length;
					dates = Number(dates);
				}
				else if(token == "AA" || token == "A")
				{
					ampm = valueString.substr(i_value,2).toUpperCase();
					if(ampm != "AM" && ampm != "PM") return null;
					i_value += 2;
				}
				else if(token == "JJ" || token == "J")
				{
					hours = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(hours)) || hours < 0 || hours > 23) return null;
					i_value += String(hours).length;
					hours = Number(hours);
				}
				else if(token == "HH" || token == "H")
				{
					hours = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(hours)) || hours < 1 || hours > 24) return null;
					i_value += String(hours).length;
					hours = Number(hours);
				}				
				else if(token == "KK" || token == "K")
				{
					hours = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(hours)) || hours < 0 || hours > 11) return null;
					i_value += String(hours).length;
					hours = Number(hours);
				}
				else if(token == "LL" || token == "L")
				{
					hours = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(hours)) || hours < 1 || hours > 12) return null;
					i_value += String(hours).length;
					hours = Number(hours);
				}
				else if(token == "NN" || token == "N")
				{
					minutes = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(minutes)) || minutes < 0 || minutes > 59) return null;
					i_value += String(minutes).length;
					minutes = Number(minutes);
				}
				else if(token == "SS" || token == "S")
				{
					seconds = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(seconds)) || seconds < 0 || seconds > 59) return null;
					i_value += String(seconds).length;
					seconds = Number(seconds);
				}
				else if(token == "QQQ" || token == "QQ" || token == "Q")
				{
					milliseconds = getIntegerValue(valueString,i_value,token.length,2);
					if(isNaN(Number(milliseconds)) || milliseconds < 0 || milliseconds > 999) return null;
					i_value += String(milliseconds).length;
					milliseconds = Number(milliseconds);
				}
			}
			else
			{
				i_format ++;
				i_value ++;
			}	
		}
 
		if (i_value != valueString.length) { return null; }
 
		if (months == 2) 
		{
			var isLeapYear:Boolean = isLeapYear(Number(years));
			if(isLeapYear && dates > 28) return null;
 
			if(!isLeapYear && dates > 29) return null;
		}
 
		if (((months == 4)||(months == 6)||(months == 9)||(months == 11)) && dates > 30) 
			return null;
 
		if(hours < 12 && ampm == "PM") {hours = (Number(hours)) + 12;}
		else if(hours > 11 && ampm == "AM") {hours = (Number(hours)) - 12};
 
		return new Date(years,(Number(months)) - 1,dates,hours,minutes,seconds,milliseconds);
	}
 
	public function getIntegerValue(dateString:String,index:int,min:int,max:int):Object
	{
		var valueString:String;
		for(var i:int = max;i >= min;i--)
		{
			valueString = dateString.substring(index,index + i);
			if(valueString.length < min) return NaN;
			if(isInteger(valueString)) return valueString;
		}
		return NaN;
	}
 
	private function isInteger(valueString:String):Boolean
	{
		var n:int = valueString.length;
		for(var i:int = 0;i < n;i++)
		{
			if(!isDigit(valueString.charAt(i)))
				return false;
		}
		return true;
	}
 
	private function isDigit(char:String):Boolean
	{
		return digits.indexOf(char) > -1;
	}
 
	private function getDayName(valueString:String,index:int):String
	{		
		var n:int = dayNames.length;
		var dayName:String;
		for(var i:int = 0;i < n;i++)
		{
			dayName = dayNames[i];
			if(valueString.substr(index,dayName.length) == dayName)
				return dayName;
		}	
		return "";
	}
 
	private function getDays(dayName:String):Number
	{		
		var day:Number = dayNames.indexOf(dayName) + 1;
		day = day > 12? day - 12:day;
		day = day == 0?NaN:day;
		return day;
	}
 
	private function getMonthName(valueString:String,index:int):String
	{
		var n:int = monthNames.length;
		var monthName:String;
		for(var i:int = 0;i < n;i++)
		{
			monthName = monthNames[i];
			if(valueString.substr(index,monthName.length) == monthName)
				return monthName;
		}	
		return "";
	}
 
	private function getMonths(monthName:String):Number
	{
		var month:Number = monthNames.indexOf(monthName) + 1;
		month = month > 12? month - 12:month;
		month = month == 0?NaN:month;
		return month;
	}
 
	private function isLeapYear(year:Number):Boolean
	{
		return ((year % 4 == 0) && (year % 100 != 0)) || ( year % 400 == 0);
	}
}

To Support Cookies, Using Flexmojos with Firefox to Run Unittests for CI Server(Hudson) in Headless Environment

Saturday, February 20th, 2010

Flexmojos is a convenient tool used to compile and test flex applications. However, when running unittests in headless linux with Hudson, I met a problem caused by cookies. The server side needs cookies to make sure requests are valid. I googled a lot and find such a solution finally.

  1. you are required to install xvfb according the instructions in this article.
  2. you must have firefox 3.x.x installed.
  3. navigate to “about:config” in firefox and set “dom.allow_scripts_to_close_windows” to “true”;
  4. register executions for flexmojos-maven-plugin like this:
    <executions>
    	<execution>
    		<id>default-test-compile</id>
    		<configuration>
    			<useNetwork>false</useNetwork>
    		</configuration>
    	</execution>
    
    	<execution>
    		<id>default-test-run</id>
    		<configuration>
    			<flashPlayerCommand>firefox</flashPlayerCommand>
    		</configuration>
    	</execution>
    </executions>
  5. download proper SWC according to the flexmojos version here. For example, I am using flexmojos 3.5.0, so I choose to download flexmojos-unittest-support-3.5.0.swc.
  6. checkout source code of flex-unittests-support with svn here.
  7. create a flex library project with flex(flash) builder called “flexmojos-unittest-support”, a sample project you can find here.

      flexmojos-unittest-support.rar (40.6 KiB, 104 hits)

  8. modify function exitFP defined in class org.sonatype.flexmojos.unitestingsupport.ControlSocket:
    		private function exitFP( event:* ):void
    		{
    			//Exiting
    			trace("Exiting");
    			if(ExternalInterface.available)
    			{
    				var functionStr:String = "function()" +
    					"{" +
    						"window.opener=null;" +
    						"window.open('','_self');" +
    						"window.close();" +
    					"}";
    
    				ExternalInterface.call(functionStr);
    			}
    			else
    			{
    				fscommand("quit");
    			}
    		}
  9. add flexmojos-unittests-support-x.x.x.swc as a library of this project.
  10. compile and build flexmojos-unittest-support.swc.
  11. install flexmojos-unittest-support.swc into maven repository according to the version of the flexmojos being used. For example, I am using flexmojos-3.5.0, so I run the command below under the bin directory of the flex library project:
    mvn install:install-file -DgroupId=org.sonatype.flexmojos -DartifactId=flexmojos-unittest-support
    -Dversion=3.5.0 -Dpackaging=swc -Dfile=flexmojos-unittest-support.swc -DcreateChecksum=true
  12. now, you can run unittests with hudson supporting cookies.

NOTE: The javascript code used to close the browser can work with firefox, can not work with IE8. I do not test the other browsers.

    Default stylesheet in an SWC (Flex Library Project), and embedded font rotation

    Thursday, February 4th, 2010

    This article comes from “Flex and ActionScript Development Tips


    For ages now I’ve been trying to figure out how I can use a StyleSheet from inside my Flex Library Project in ActionScript. I kept reading that it is very resource intensive to be calling UIComponent.setStyle(…) at runtime, so I wanted to set all my styles using a StyleSheet. The LiveDocs on the subject seem to say that there are two ways to load a StyleSheet:

    1. From inside MXML in your Application using the <Style source=”assets/styles.css“/> tag
    2. By loading an external stylesheet SWF file (compiled from a CSS file) using the
      StyleManager. loadStyleDeclarations(url)

    Then I finally found the solution in this article (right near the bottom of the page in the comment by Henk). And that pointed me to this LiveDoc - Applying styles to your custom component which solved the problem. Scroll most of the way down until you get to the part called “Applying styles from a defaults.css file”.

    If you don’t want to read the articles above, here is my brief summary.

    Using a StyleSheet in your FlexLibrary Project:

    1. create a StyleSheet in the src directory of your project, and call it defaults.css
    2. open the project Properties > Flex Library Build Path and check the src/defaults.css file under the Assets tab
    3. define your styles inside the defaults.css StyleSheet

    Restrictions:

    • You can include only a single style sheet in the SWC file
    • The file must be named defaults.css
    • The file must be in the top-most directory of the SWC file

    *Note: it appears that having a defaults.css file in your Flex Application project (swf) also works without having to specify the stylesheet in the mxml (e.g. <mx:Style source=”defaults.css“/> is not needed).

    Using Embedded Fonts inside Flex Library Project/SWC:
    If you want to use an embedded font inside your library project you have two ways of doing this:

    1. Embed the font inside an ActionScript file like this (the font is inside the project src/assets directory):
      [Embed(source='/assets/verdana.ttf'fontName='localVerdana',
      mimeType='application/x-font')]
      public var verdanaFont:Class;

      setStyle(“fontFamily”, “localVerdana”);
    2. Or put your embedded ttf font in your project’s src directory and embed the fond using the defaults.css file (the font must be in the src directory for this to work - see this Adobe Bug for more details):
      defaults.css:

      @font-face {
      font-familylocalVerdana;
      font-weightnormal;
      srcurl(“verdana.ttf”);
      }
      .label {
      /* must use embedded font for label rotation to work */
      font-familylocalVerdana;
      /* must specifically set the font weight */
      font-weightnormal;
      }

    Note that if you want to set the DisplayObject.rotation property then you have to use an embedded font otherwise it doesn’t work.

    Here is a simple example of font/label rotation (right click “View Source” for the code).
    In this example I actually included three fonts - Verdana plainVerdana bold, and Comic Sans.

    * Note that fonts can greatly increase the size of your SWF. The three fonts that I used above are all about 150 KB each. One way to reduce the size of your SWF is to restrict the unicode character range (meaning that only part of the font set is included in your SWF). Here is the LiveDoc on Using Fonts and Setting Character Ranges.