Thursday, September 30, 2010

Using the RadioButton component: Part 2

Today we will learn how to create a simple quiz. Everything is done with AS3.

Here's the final result:


First we have to import all the necessary classes. We will be using RadioButtons, Buttons and TextFields.

import fl.controls.RadioButton;
import flash.text.TextField;
import fl.controls.Button;

Next, we set up the first question and 2 radio buttons. We set RadioButtons' positions using the move(); method and we need to remember to give them the same groupName.

var rb1:RadioButton = new RadioButton();
addChild(rb1);
rb1.move(10, 40);
rb1.label="Yes";
rb1.groupName="rg1";

var rb2:RadioButton = new RadioButton();
addChild(rb2);
rb2.move(60, 40);
rb2.label="No";
rb2.groupName="rg1";

var q:TextField = new TextField();
addChild(q);
q.x = q.y = 10;
q.text="Do you own a car?";
q.height=20;
q.width=130;
q.selectable=false;

Pretty much the same with the second question:

var rb3:RadioButton = new RadioButton();
addChild(rb3);
rb3.move(10, 100);
rb3.label="Yes";
rb3.groupName="rg2";

var rb4:RadioButton = new RadioButton();
addChild(rb4);
rb4.move(60, 100);
rb4.label="No";
rb4.groupName="rg2";

var q2:TextField = new TextField();
addChild(q2);
q2.x = 10;
q2.y = 80;
q2.text="Do you own a house?";
q2.height=20;
q2.width=130;
q2.selectable=false;

Now we add our submit button. Once again, we're using move() to set the position.

var submitBtn:Button = new Button();
addChild(submitBtn);
submitBtn.move(10,140);
submitBtn.label="Submit";

The output text field needs to have wordWrap set to true, so the text doesn't cut off.

var outputT:TextField = new TextField();
addChild(outputT);
outputT.width=outputT.height=180;
outputT.wordWrap=true;
outputT.selectable=false;
outputT.x = 130;
outputT.y = 30;

And finally, the listener and function for the submit button press.

submitBtn.addEventListener(MouseEvent.CLICK, submitResults);

function submitResults(MouseEvent):void{
if((rb1.selected || rb2.selected)&&(rb3.selected || rb4.selected)){
outputT.text="The person "
outputT.appendText((rb1.selected)?("owns a car"):("doesn't own a car"));
outputT.appendText((rb3.selected)?(" and owns a house."):(" and doesn't own a house."));
}else{
outputT.text="Some questions are not answered."
}
}

The code is pretty simple and you now know how to use the RadioButton component using only AS3. This is especially useful if you need to make an application with Flex.

Thanks for reading!

Related:

Using RadioButton component: Part 1
Using RadioButton component: Part 3

No comments:

Post a Comment