Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
104
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Appendix A

}

}

deleteButton.addEventListener(“click”, handleDeleteListener);

// Handle pressing the Add button

var handleAddListener:Object = new Object(); handleAddListener.click = function()

{

notesList.push({title:titleField.text, size:noteTextField.text.length, ; text:noteTextField.text});

notesDataGrid.selectedIndex = notesList.length - 1; deleteButton.enabled = true;

}

addButton.addEventListener(“click”, handleAddListener);

// Handle pressing the Save button

var handleSaveListener:Object = new Object(); handleSaveListener.click = function()

{

notesDataGrid.editField(notesDataGrid.selectedIndex, “title”, titleField.text); notesDataGrid.editField(notesDataGrid.selectedIndex, “size”, ;

noteTextField.text.length); notesDataGrid.editField(notesDataGrid.selectedIndex, “text”, ;

noteTextField.text);

}

saveButton.addEventListener(“click”, handleSaveListener);

Chapter 11

Exercise 1 Solution

import mx.controls.Button; import mx.controls.DataGrid; import mx.controls.Label; import mx.controls.TextInput; import mx.controls.TextArea;

import mx.styles.CSSStyleDeclaration;

var notesList:Array = new Array();

notesList.push({title:”Note 1”, size:0, text:”The quick brown fox...”}); notesList.push({title:”Note 2”, size:0, text:”The quick brown...”}); notesList.push({title:”Note 3”, size:0, text:”The quick fox...”});

notesList[0].size = notesList[0].text.length; notesList[1].size = notesList[1].text.length; notesList[2].size = notesList[2].text.length;

function drawScreen():Void

{

this.createClassObject(Label, “gridTitle”, this.getNextHighestDepth()); gridTitle.text = “Notes”;

gridTitle._x = 18; gridTitle._y = 18;

this.createClassObject(DataGrid, “notesDataGrid”, this.getNextHighestDepth());

718

Exercise Answers

notesDataGrid._x = 18; notesDataGrid._y = 40; notesDataGrid.setSize(225, 170);

notesDataGrid.addColumn(“title”);

notesDataGrid.addColumn(“size”); notesDataGrid.getColumnAt(0).width = 165; notesDataGrid.getColumnAt(0).headerText = “Title”; notesDataGrid.getColumnAt(1).headerText = “Size”; notesDataGrid.dataProvider = notesList;

this.createClassObject(Button, “addButton”, this.getNextHighestDepth()); addButton.label = “Add”;

addButton._x = 18; addButton._y = 219; addButton.setSize(100, 22);

this.createClassObject(Button, “deleteButton”, this.getNextHighestDepth()); deleteButton.label = “Delete”;

deleteButton._x = 142; deleteButton._y = 219; deleteButton.setSize(100, 22); deleteButton.enabled = false;

this.createClassObject(Label, “noteTitle”, this.getNextHighestDepth()); noteTitle.text = “Title”;

noteTitle._x = 272; noteTitle._y = 18;

this.createClassObject(TextInput, “titleField”, this.getNextHighestDepth()); titleField._x = 272;

titleField._y = 40; titleField.setSize(225, 22);

this.createClassObject(Label, “textTitle”, this.getNextHighestDepth()); textTitle.text = “Text”;

textTitle._x = 272; textTitle._y = 88;

this.createClassObject(TextArea, “noteTextField”, this.getNextHighestDepth()); noteTextField._x = 272;

noteTextField._y = 109; noteTextField.setSize(225, 100); noteTextField.wordWrap = true;

this.createClassObject(Button, “saveButton”, this.getNextHighestDepth()); saveButton.label = “Save”;

saveButton._x = 395; saveButton._y = 219; saveButton.setSize(100, 22); saveButton.enabled = false;

// Set global styles _global.style.setStyle(“themeColor”, 0xAAAAEE); _global.style.setStyle(“fontFamily”, “Verdana”); _global.style.setStyle(“fontSize”, 11);

719

Appendix A

_global.style.setStyle(“color”, 0x666666);

// Set component styles

_global.styles.Label = new CSSStyleDeclaration(); _global.styles.Label.setStyle(“fontSize”, 14); _global.styles.Label.setStyle(“fontWeight”, “bold”); _global.styles.Label.setStyle(“color”, 0x000000);

_global.styles.Button = new CSSStyleDeclaration(); _global.styles.Button.setStyle(“fontWeight”, “bold”); _global.styles.Button.setStyle(“color”, 0x333399); _global.styles.Button.setStyle(“buttonColor”, 0xAAAAEE);

// Set individual instance styles notesDataGrid.setStyle(“vGridLines”, false); notesDataGrid.setStyle(“hGridLines”, false); notesDataGrid.setStyle(“headerColor”, 0xBBBBFF);

var headerStyle = new CSSStyleDeclaration(); headerStyle.setStyle(“fontWeight”, “bold”); notesDataGrid.setStyle(“headerStyle”, headerStyle);

deleteButton.setStyle(“color”, 0x990000);

}

drawScreen();

//Handle the user typing into the title or note fields var handleNoteChangeListener:Object = new Object(); handleNoteChangeListener.change = function()

{

saveButton.enabled = true;

}

titleField.addEventListener(“change”, handleNoteChangeListener); noteTextField.addEventListener(“change”, handleNoteChangeListener);

//Handle the selecting of a note from the list

var handleNoteListener:Object = new Object(); handleNoteListener.change = function(eventObject:Object)

{

titleField.text = eventObject.target.selectedItem.title; noteTextField.text = eventObject.target.selectedItem.text; deleteButton.enabled = true;

}

notesDataGrid.addEventListener(“change”, handleNoteListener);

// Handle the pressing of the Delete button var handleDeleteListener:Object = new Object(); handleDeleteListener.click = function()

{

trace(“selectedIndex: “ + notesDataGrid.selectedIndex); var selectedRow:Number = notesDataGrid.selectedIndex; notesList.splice(selectedRow, 1); notesDataGrid.dataProvider = notesList;

// Alternately, the following line can replace the previous two

720

Exercise Answers

// notesDataGrid.dataProvider.removeItemAt(selectedRow);

if (notesList.length > 0)

{

// The list is not empty

if (selectedRow < notesList.length)

{

// Select the row that takes the deleted row’s place notesDataGrid.selectedIndex = selectedRow;

}

else

{

//There are no more rows to take the selected

//row’s place. Select the last row. notesDataGrid.selectedIndex = notesList.length - 1;

}

notesDataGrid.dispatchEvent({type:”change”, target:notesDataGrid});

}

else

{

// The list is empty. deleteButton.enabled = false;

}

}

deleteButton.addEventListener(“click”, handleDeleteListener);

// Handle pressing the Add button

var handleAddListener:Object = new Object(); handleAddListener.click = function()

{

notesDataGrid.addItem({title:”New note”, size:0, text:””}); notesDataGrid.selectedIndex = notesList.length - 1; titleField.text = “New note”;

noteTextField.text = “”; deleteButton.enabled = true;

}

addButton.addEventListener(“click”, handleAddListener);

// Handle pressing the Save button

var handleSaveListener:Object = new Object(); handleSaveListener.click = function()

{

notesDataGrid.editField(notesDataGrid.selectedIndex, “title”, titleField.text); notesDataGrid.editField(notesDataGrid.selectedIndex, “size”, ;

noteTextField.text.length); notesDataGrid.editField(notesDataGrid.selectedIndex, “text”,;

noteTextField.text);

}

saveButton.addEventListener(“click”, handleSaveListener);

Exercise 2 Solution

1.Open the file SampleTheme.fla at <application root>/Configuration/ComponentFLA/.

721

Appendix A

2.Open the Library panel and select the movie clip SampleTheme in the Flash UI Components 2 folder. From the menu at the top right of the Library panel, select Copy.

3.Switch to the Flash file that you want to re-skin. From the menu at the top right of the Library panel for that Flash file, select Paste.

4.Navigate through the folder structure that is automatically added to the library looking for the component you want to re-skin. Note that some components are shared. For instance, the Button component is re-skinned by modifying the SimpleButton component.

5.Experiment away!

Chapter 12

Exercise 1 Solution

The if statement can be separated around the && operator:

if (shipType == “hospital” || shipConfiguration == “peacetime”)

{

if (shipDirection == “east” || shipDirection == “west”)

{

// do stuff

}

}

Exercise 2 Solution

The getYear() method returns the current year minus 1900, so 2006 is represented as 106. Either change the year to 106 in the condition, or change to the getFullYear() method that returns the year value that you would normally expect.

var tempDate:Date = new Date(2006, 11, 20);

if (tempDate.getMonth() > 5 && tempDate.getMonth() < 11)

{

// Stuff goes here

}

else if (tempDate.getFullYear() == 2006 && tempDate.getMonth() == 11)

//or

//else if (tempDate.getYear() == 106 && tempDate.getMonth() == 11)

{

trace(“You should see this text”); // Stuff goes here

}

else

{

// Stuff goes here

}

Exercise 3 Solution

There is an issue with the depth value being passed into the createEmptyMovieClip() method. Each call is reusing the same depth, so the previous movie clip gets deleted. Also, two of the lineTo() methods are reversed, causing the corners of the square to be drawn out of order.

722

Exercise Answers

var movieClipHandle:MovieClip;

var baseMovieClip:MovieClip = _level0; var numMovieClips:Number = 3;

for (var i:Number = 0; i < numMovieClips; i++)

{

baseMovieClip.createEmptyMovieClip(“movieClip” + i, i); movieClipHandle = baseMovieClip[“movieClip” + i]; movieClipHandle._x = i * 30 + 20;

movieClipHandle._y = 20; movieClipHandle.lineStyle(1, 0x000000, 100); movieClipHandle.moveTo(0, 0); movieClipHandle.lineTo(0, 20); movieClipHandle.lineTo(20, 20); movieClipHandle.lineTo(20, 0); movieClipHandle.lineTo(0, 0);

}

Exercise 4 Solution

There are two issues with this code. The first is the infinite loop. By tracing through the loop with the debugger, the fact that the i++ line only is called some of the time is what causes this problem. Pulling it out of the if statement fixes this. The problem with the array not being populated with data is that the array has not been initialized. This can be found either by watching the array through the debugger, or tracing the array itself. The bold lines in the following code are the ones that have been changed to fix the problems with the loop.

var stopCharacter:String = “.”;

var paragraphText:String = “The quick brown fox. Jumped over the lazy dog. ; Again. And again.”;

var sentenceText:String = “”;

var sentenceArray:Array = new Array(); var i:Number = 0;

while (i < paragraphText.length)

{

if (paragraphText.charAt(i) == stopCharacter)

{

sentenceArray.push(sentenceText); sentenceText = “”;

}

else

{

sentenceText += paragraphText.charAt(i);

}

i++;

}

for (var i = 0; i < sentenceArray.length; i++)

{

trace(i + “: “ + sentenceArray[i]);

}

723

Appendix A

Exercise 5 Solution

There are three issues with this code. First, every click results in both button handlers being called. The problem here is the confusion between onRelease and onMouseUp. The onMouseUp event is a global event that fires when the mouse is released, regardless of where it is located, whereas the onRelease event only fires when the mouse was released over the target movie clip. The trace statements made it clear that they were both firing, and commenting out the event handler would have made it clear that the origin of the problem was there.

Second, the label text was not showing up. The debugger shows all the properties that have been set, and it shows that it is visible and is within the bounds of the stage. It also shows a label property set, but no text property set. The label property is not a valid text field property; the text property is the one that should be set.

Finally, the problem with the background color is that AAAAFF is not a valid data type; it should be a hexadecimal number in the form of 0xAAAAFF. Tracing the boxColor argument results in an undefined value, indicating the nature of the problem.

function invokePlay():Void

{

trace(“Pressed play”);

}

function invokeStop():Void

{

trace(“Pressed stop”);

}

function createButton(parentMovieClip:MovieClip, buttonName:String, ; buttonLabel:String, xPos:Number, yPos:Number, buttonWidth:Number, ; buttonHeight:Number, callback:Function):Void

{

var buttonHandle:MovieClip; parentMovieClip.createEmptyMovieClip(buttonName, ;

parentMovieClip.getNextHighestDepth()); buttonHandle = parentMovieClip[buttonName]; buttonHandle.onRelease = function()

{

callback();

}

buttonHandle._x = xPos; buttonHandle._y = yPos;

drawBox(buttonHandle, buttonWidth, buttonHeight, 0xAAAAFF, 0x333333); buttonHandle.createTextField(“labelField”, 1, 4, 4, 50, 15); buttonHandle.labelField.text = buttonLabel;

}

function drawBox(targetMovieClip:MovieClip, boxWidth:Number, boxHeight:Number, ; boxColor:Number, lineColor:Number):Void

{

targetMovieClip.beginFill(boxColor); targetMovieClip.lineStyle(1, lineColor); targetMovieClip.moveTo(0, 0); targetMovieClip.lineTo(boxWidth, 0); targetMovieClip.lineTo(boxWidth, boxHeight);

724

Exercise Answers

targetMovieClip.lineTo(0, boxHeight); targetMovieClip.lineTo(0, 0);

}

createButton(this, “playButton”, “Play”, 10, 10, 70, 20, invokePlay); createButton(this, “stopButton”, “Stop”, 90, 10, 35, 20, invokeStop);

Chapter 13

Exercise 1 Solution

//Place this AS file in the class path of the FLA:

class Circle{

static function getRadians(degrees):Number { return degrees*(Math.PI/180);

}

static function getCirclePoints(points, diameter, callBackOwner, ; callback):Array {

var ary = []; var newTheta = 0;

var theta = 360/points;

for (var i = 0; i<points; i++) { ary[i] = [];

newTheta += theta;

var rad = Circle.getRadians(newTheta); ary[i][0] = (Math.cos(rad)*diameter); ary[i][1] = (Math.sin(rad)*diameter);

callback.apply(callBackOwner,[ary[i]]);

}

return ary;

}

}

Place this code on frame 1 of the FLA:

var circleHolder = this.createEmptyMovieClip(“clip1”, this.getNextHighestDepth()); circleHolder.points = Circle.getCirclePoints(45, 100);

with (circleHolder) { moveTo(points[0][0], points[0][1]); lineStyle(2, 0xFF0000, 100);

for (var i = 1; i<points.length; i++) { lineTo(points[i][0], points[i][1]);

}

lineTo(points[0][0], points[0][1]);

}

Exercise 2 Solution

function makeCanvas(handle, w, h) { with (handle) {

beginFill(0xFFFFFF, 100); lineStyle(0, 0xCCCCCC, 100); moveTo(0, 0);

lineTo(0, h); lineTo(w, h);

725

Appendix A

lineTo(w, 0); lineTo(0, 0); endFill();

}

handle.lineStyle(0, 0x666666, 100); handle.drawLine = function(){

if(oldX != this._xmouse && oldY != this._ymouse){ this.lineTo(this._xmouse,this._ymouse);

oldX = this._xmouse; oldY = this._yMouse;

}

updateAfterEvent();

}

handle.onPress = function(){

this.drawing = setInterval(this,”drawLine”,10); this.moveTo(this._xmouse,this._ymouse);

}

handle.onRelease = handle.onReleaseOutside = function(){ clearInterval(this.drawing);

}

}

drawingArea = this.createEmptyMovieClip(“clip1”, this.getNextHighestDepth()); makeCanvas(drawingArea,400,300);

Exercise 3 Solution

image = this.createEmptyMovieClip(“clip1”, 0);

var preloader:Object = new Object();

preloader.onLoadComplete = function(clip:MovieClip) { image.setMask(maskClip);

};

var image_load:MovieClipLoader = new MovieClipLoader(); image_load.addListener(preloader); image_load.loadClip(“myImage.jpg”, image);

maskClip = this.createEmptyMovieClip(“clip2”, 1); with (maskClip) {

beginFill(0xFF0000, 60); lineStyle(2, 0x666666, 100); moveTo(20, 20);

lineTo(20, 120); lineTo(120, 120); lineTo(120, 20); lineTo(20, 20); endFill();

}

726

Exercise Answers

Chapter 14

Exercise 1 Solution

//Import the BitmapData class import flash.display.*;

//Create a MovieClip containter

var myButton = this.createEmptyMovieClip (“button1”, this.getNextHighestDepth ());

//Define default state

var myButtonBitmap = BitmapData.loadBitmap (“libraryBitmapOffState”); myButton.attachBitmap (myButtonBitmap, 0);

//Associate button states with library items var linkageIDoffState = “libraryBitmapOffState”;

var linkageIDoverState = “libraryBitmapOverState”; var linkageIDhitState = “libraryBitmapHitState”;

//Define button states

myButton.onRollOver = function () {

var myButtonBitmap = BitmapData.loadBitmap (linkageIDoverState); this.attachBitmap (myButtonBitmap, 0);

};

myButton.onRollOut = function () {

var myButtonBitmap = BitmapData.loadBitmap (linkageIDoffState); this.attachBitmap (myButtonBitmap, 0);

};

myButton.onPress = function () {

var myButtonBitmap = BitmapData.loadBitmap (linkageIDhitState); this.attachBitmap (myButtonBitmap, 0);

};

myButton.onRelease = myButton.onReleaseOutside = function () {

var myButtonBitmap = BitmapData.loadBitmap (linkageIDoffState); this.attachBitmap (myButtonBitmap, 0);

};

Exercise 2 Solution

Place an instance of the Button component in the library and then add the following ActionScript to frame 1 of root:

import flash.filters.*;

var navShadow:DropShadowFilter = new DropShadowFilter (); navShadow.blurX = 10;

navShadow.blurY = 10;

navShadow.alpha = .3; navShadow.angle = 45; navShadow.color = ox000000; navShadow.distance = 5;

727