Sunday, October 3, 2010

Using the ComboBox component: Part 2

Today we will learn how to work with the ComboBox component using AS3.

Here's what we will create:


First of all we need to import all the necessary classes. We will be using ComboBox, DataProvider and TextField.

import fl.controls.ComboBox;
import fl.data.DataProvider;
import flash.text.TextField;

Create a ComboBox object and add it to the stage. Set a promt and move it to a specific location:

var myComboBox:ComboBox = new ComboBox();
addChild(myComboBox);
myComboBox.move(20,50);
myComboBox.prompt="Select a fruit";

Now for the dataProvider. This will be the array where all the data is stored. Each item in the combo box has two properties: label and data. Label is what will show up in the list, and data is a variable, that isn't visible to the user. In this example, I just set each item's data to its number in the list.

var myItems:Array = [
{label: "Apple", data: 1}, 
{label: "Banana", data: 2}, 
{label: "Orange", data: 3}, 
{label: "Pineapple", data: 4}
];

myComboBox.dataProvider = new DataProvider(myItems);

Finally, we add the text field and an Event.CHANGE listener with a function:

var textF:TextField = new TextField();
textF.text="No fruit selected"
addChild(textF);
textF.x=20
textF.y=20
textF.height=20
textF.width=100
textF.selectable=false;

myComboBox.addEventListener(Event.CHANGE, onAddItem);

function onAddItem(event:Event):void {
textF.text="Fruit Number " + event.target.selectedItem.data + "."
}

So, here's the final code:

import fl.controls.ComboBox;
import fl.data.DataProvider;
import flash.text.TextField;

var myComboBox:ComboBox = new ComboBox();
addChild(myComboBox);
myComboBox.move(20,50);
myComboBox.prompt="Select a fruit";

var myItems:Array = [
{label: "Apple", data: 1}, 
{label: "Banana", data: 2}, 
{label: "Orange", data: 3}, 
{label: "Pineapple", data: 4}
];

myComboBox.dataProvider = new DataProvider(myItems);

var textF:TextField = new TextField();
textF.text="No fruit selected"
addChild(textF);
textF.x=20
textF.y=20
textF.height=20
textF.width=100
textF.selectable=false;

myComboBox.addEventListener(Event.CHANGE, onAddItem);

function onAddItem(event:Event):void {
textF.text="Fruit Number " + event.target.selectedItem.data + "."
}

Thanks.

Related:

Using ComboBox component: Part 1

No comments:

Post a Comment