自作コンポーネントを作る
最後に自作コンポーネントを作る方法を簡単にご紹介しましょう。前回作った
まずは完成形のFlashをご覧ください。次のようになります。
フォントサイズを動的に変えられるようになりました。前回よりもアプリケーションっぽくなりましたね。
ソースコードは次の3つのファイルから成り立っています。
ビルドするには,
mxmlc ComponentTest.mxml
LogoGeneratorコンポーネントの埋め込み
それでは,
<?xml version="1.0" encoding="UTF-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:comp="*"> <!-- (1) -->
<mx:Panel width="100%" height="100%"
title="Logo Generator (Flex version)"
:
:
<mx:Canvas width="100%" height="100%"
borderColor="0xcccccc" borderStyle="solid">
<comp:LogoGenerator id="logo"/> <!-- (2) -->
</mx:Canvas>
</mx:Panel>
</mx:Application>
<mx:Application>タグに
(2)
TextInputコンポーネントとHSliderコンポーネントでは,
TextInput の change イベント処理
<mx:TextInput id="input1" text="Logo Generator"
:
change="logo.text = input1.text"/>
HSliderのchangeイベント処理
<mx:HSlider id="slider"
:
change="logo.fontSize = slider.value"/>
全てのコンポーネントはUIComponentクラスを継承する
次に,
前回作成したLogoGeneratorクラスはSpriteを継承していましたが,
import mx.core.UIComponent;
// LogoGenerator クラス
public class LogoGenerator extends UIComponent {
プロパティの定義
コンポーネントらしくするために,
textプロパティは次のように定義しています。
// text プロパティの実体
private var _text:String; // (1)
// text プロパティの getter
public function get text():String { // (2)
return _text;
}
// text プロパティの setter
public function set text(value:String):void { // (3)
_text = value;
update();
}
プロパティは,
getterはtextプロパティを取得するときに呼ばれるメソッドです。functionのあとに,
setterはtextプロパティの値に代入されるときに呼ばれるメソッドです。functionのあとに
update()メソッドの修正
update()メソッドはtextプロパティの値を表示するように,
また,
Flexフレームワークはサイズが変わったという通知を受けると,
protected override function measure():void {
measuredWidth = badge.x + badge.width;
measuredHeight = reflection.y + reflection.height;
}
measuredWidthおよびmeasuredHeightプロパティにサイズを設定することで,
まとめ
だいぶ駆け足でしたが,
Flexはコンポーネントも豊富で奥も深いので,
次回は最終回です。今,