I am new to AS3. When learning AS3, I get the below code from an Adobe example and trying to run it gives an error like
"1037: Packages cannot be nested."
What does this mean?
Please tell me how to execute? or any problem in this code?
package {
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
public class TextField_alwaysShowSelection extends Sprite {
public function TextField_alwaysShowSelection() {
var label1:TextField = createTextField(0, 20, 200, 20);
label1.text = "This text is selected.";
label1.setSelection(0, 9);
label1.alwaysShowSelection = true;
var label2:TextField = createTextField(0, 50, 200, 20);
label2.text = "Drag to select some of this text.";
}
private function createTextField(x:Number, y:Number, width:Number, height:Number):TextField {
var result:TextField = new TextField();
result.x = x; result.y = y;
result.width = width; result.height = height;
addChild(result);
return result;
}
}
}
You need to create an action script file and then add that class to document class in your fla file property then it would not give you an error
Your code should compile, provided that it is in the root source folder ("src" in flex builder). Are you sure that's the entire file?
The error means that you have nested a package {} statement inside another package {} statement.
If you want to include the AS3 in the timeline itself, use this:
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
function TextField_alwaysShowSelection() {
var label1:TextField = createTextField(0, 20, 200, 20);
label1.text = "This text is selected.";
label1.setSelection(0, 9);
label1.alwaysShowSelection = true;
var label2:TextField = createTextField(0, 50, 200, 20);
label2.text = "Drag to select some of this text.";
}
function createTextField(x:Number, y:Number, width:Number, height:Number):TextField {
var result:TextField = new TextField();
result.x = x; result.y = y;
result.width = width; result.height = height;
addChild(result);
return result;
}
How are you running this file? This is not a complete file. If you are working with flex then you need the supported MXML code. However the error indicates that you are working with src folder. It would be good if you give the complete procedure.
If you are using Flash, put that code in a file named "TextField_alwaysShowSelection.as", place it next to your FLA and set that class name as the DocumentClass in the "properties" panel of your FLA... so where it says "Class:" write "TextField_alwaysShowSelection".
Related
Can I check if I'm using an actual font when I create TextFormat/TextField ? If I specify a not embedded font or use any random string, no text is displayed and I don't know why.
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class SimpleSprite extends Sprite
{
//[Embed(source="C:/Windows/Fonts/Arial.ttf",fontName="default_font",mimeType="application/x-font",fontWeight="normal",fontStyle="normal",advancedAntiAliasing="true",embedAsCFF="false")]
//private static var defaultFont: String;
public function SimpleSprite()
{
var t: TextField = new TextField;
t.autoSize = TextFieldAutoSize.LEFT;
t.defaultTextFormat = new TextFormat("default_font", 16, 0xff0000);
t.embedFonts = true;
t.text = "hello world";
addChild(t);
}
}
It doesn't display any text when the embed lines are missing.
Important: My package that creates TextFields does not embed anything and I wish to keep it that way. The embedding must be done by the programmer who uses the package. I want to check if the font is embedded and throw an error if not.
You can use Font.enumerateFonts which will return an array of available embedded fonts. You could use that to create a function like the following:
private function hasEmbeddedFont(fontName:String):Boolean
{
var fonts:Array = Font.enumerateFonts();
for each(var font:Font in fonts)
{
if (font.fontName == fontName)
{
return true;
}
}
return false;
}
And then use it something like this:
t.autoSize = TextFieldAutoSize.LEFT;
t.defaultTextFormat = new TextFormat("default_font", 16, 0xff0000);
t.embedFonts = hasEmbeddedFont("default_font");
t.text = "hello world";
If you're building a library for others to use, you might consider abstracting it into your own custom subclass of TextField so it's all handled automatically.
I am loading an external swf file into a parent swf file.
Previously, I was getting error 1009 and fixed that by using a listener event to add the swf to the stage before running any scripts.
The swf however fails to load completely when embedded into a parent swf as seen in this URL
http://viewer.zmags.com/publication/06b68a69?viewType=pubPreview#/06b68a69/1
Here is the code I am using.
Thank you for any input.
package
{
import com.greensock.TweenLite;
import flash.display.DisplayObject;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.SpreadMethod;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class slider5 extends Sprite
{
public var thumbPath:String = "Trailchair_thumb";
public var featPath:String = "Trailchair";
public var sliderIndex:Number = 1;
public var currBg:Bitmap = new Bitmap();
public var thumbCount:Number = 8;
public var thumbHolder:Sprite = new Sprite();
public var thumbMask:Sprite = new Sprite();
public var thumbX:Number = 0;
public var thmPadding:Number = 10;
public var thmWidth:Number;
public var navLeft:Sprite = new Sprite();
public var navRight:Sprite = new Sprite();
public var timer:Timer = new Timer(5000,0);
public var sliderDir:String = "fwd";
public function slider5()
{
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function onAddedToStage(e:Event):void{
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
//THE BACKGROUND IMAGE
currBg.alpha = 1;
stage.addChildAt(currBg, 0);
changeBg(sliderIndex);
//The thumbMask a sprite with graphic rectangle
thumbMask.x = 87;
thumbMask.y = 572;
thumbMask.graphics.beginFill(0xFFFFFF);
thumbMask.graphics.drawRect(0,0, 406, 181);
stage.addChildAt(thumbMask, 2);
//The thumbSlider
thumbHolder.x = 228;
thumbHolder.y = 573;
stage.addChildAt(thumbHolder, 1);
thumbHolder.mask = thumbMask;
buildThumbs();
//add the nav
navLeft.x = 100;
navLeft.y = 609;
navRight.x = 496;
navRight.y = 609;
stage.addChildAt(navLeft, 4);
stage.addChildAt(navRight, 4);
var navBmp:Bitmap = new Bitmap();
navBmp.bitmapData = new navarrow(109,109);
var navBmp_Rt:Bitmap = new Bitmap();
navBmp_Rt.bitmapData = new navarrow(109,109);
navLeft.addChild(navBmp);
navLeft.scaleX *= -1;
navRight.addChild(navBmp_Rt);
navLeft.useHandCursor = true;
navLeft.buttonMode = true;
navRight.useHandCursor = true;
navRight.buttonMode = true;
navLeft.name = "left";
navRight.name = "right";
navLeft.addEventListener(MouseEvent.CLICK, navClick);
navRight.addEventListener(MouseEvent.CLICK, navClick);
//add the active item frame
var frame:Sprite = new Sprite();
frame.x = 226;
frame.y = 570;
frame.graphics.lineStyle(10, 0x000000);
frame.graphics.drawRect(0,0,131, 181);
stage.addChildAt(frame, 6);
timer.addEventListener(TimerEvent.TIMER, timeEvt);
timer.start();
}
public function changeBg(index):void
{
//set the first slide from our library and add to the stage
var currBg_Class:Class = getDefinitionByName( featPath + index ) as Class;
currBg.bitmapData = new currBg_Class(597,842);
//fade it in
TweenLite.from(currBg, 0.5, {alpha:0});
}
public function buildThumbs():void
{
var currThm:Class;
for (var i:uint = 1; i<=thumbCount; i++)
{
currThm = getDefinitionByName( thumbPath + i ) as Class;
var thmBmp:Bitmap = new Bitmap();
thmBmp.bitmapData = new currThm(126,176);
thmBmp.x = thumbX;
thumbHolder.addChild(thmBmp);
thumbX += thmBmp.width + thmPadding;
}
thmWidth = thmBmp.width + thmPadding;
}
public function navClick(e):void
{
timer.reset();
timer.start();
var dir:String = e.currentTarget.name;
if (dir=="left" && thumbHolder.x < 228 )
{
sliderIndex--;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x + thmWidth});
//thumbHolder.x = thumbHolder.x + thmWidth;
}
else if (dir=="right" && thumbHolder.x > - 724 )
{
sliderIndex++;
TweenLite.to(thumbHolder, 0.5, {x:thumbHolder.x - thmWidth});
//thumbHolder.x = thumbHolder.x - thmWidth;
}
if (sliderIndex == thumbCount)
{
sliderDir = "bk";
}
if (sliderIndex == 1)
{
sliderDir = "fwd";
}
changeBg(sliderIndex);
}
public function timeEvt(e):void
{
if (sliderDir == "fwd")
{
navRight.dispatchEvent(new Event(MouseEvent.CLICK));
}
else if (sliderDir == "bk")
{
navLeft.dispatchEvent(new Event(MouseEvent.CLICK));
}
}
}
}
If you still need it you can try these two suggestions. Note I didnt know about Zmags and initially assumed that it was your own domain name. That's why I suggested you use the Loader class. It worked for me when I did a test version of a parent.swf' that loaded a test 'child.swf' containing your code. It actually loaded the child swf without problems.
Change from extending Sprite to extending MovieClip
Avoid checking for added to stage in this project
Explanations:
Extending MovieClip instead of Sprite
I Long story short Flash wont like your swf extending Sprite then being opened by a parent loader that extends Movieclip. The ZMag player will be extending MovieClip. It's logical and the docs do confirm this in a way. Whether it fixes your issue or not just keep it MovieClip when using ZMags.
Avoiding Stage referencing in your code..
Looking at this Zmags Q&A documentaion:
http://community.zmags.com/articles/Knowledgebase/Common-questions-on-flash-integration
Looking at Question 4.. In their answer these two stand out.
Reference of the stage parameter in the uploaded SWF conflicting with the publication
Badly or locally referenced resources in the SWF you uploaded which cannot be found
Is it really necessary to have an added_to_stage check in this? If it wont hurt then I suggest dropping the stage_added checking from function slider5() and instead cut/paste in there the code you have from the function onAddedToStage(e:Event).
Hope it helps.
Hi this might seem like a stupid but i'm a student trying to make an augmented reality application and i found this toolkit for AR stuff which i've brought into flash builder but i've never really used any external toolkits before and i'm not really sure what i'm doing.
At the moment it keeps saying that it's trying to access an undefined property # ar_cam, ar_vid, ar_marker, & ar_params.
I'm not sure if i am doing something wrong or if it has something to do with how i am using the external toolkit.
Any advice anybody could give me with this would be greatly appreciated.
This is my code so far:
package
{
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.ByteArray;
import org.libspark.flartoolkit.core.FLARCode;
import org.libspark.flartoolkit.core.param.FLARParam;
[SWF(width="320", height="480", frameRate="30", backgroundColor="#FFFFFF")]
public class Main extends Sprite
{
[Embed(source="marker.pat", mimeType="application/octet-stream")]
private var marker:Class;
[Embed(source="camera_para.dat", mimeType="application/octet-stream")]
private var cam_params:Class;
public function Main()
{
createFLAR();
createCam();
}
public function createFLAR()
{
ar_params = new FLARParam();
ar_marker = new FLARCode(16, 16);
ar_params.loadARParam(new cam_params() as ByteArray);
ar_marker.loadARPatt(new marker());
}
public function createCam()
{
ar_vid = new Video(320, 480);
ar_cam = Camera.getCamera();
ar_cam.setMode(320, 480, 30);
ar_vid.attachCamera(ar_cam);
addChild(ar_vid);
}
}
}
You're not creating the variables for the objects in either of those functions so replace
ar_params = new FLARParam();
ar_marker = new FLARCode(16, 16);
with
var ar_params:FLARParam = new FLARParam();
var ar_marker:FLARCode = new FLARCode(16, 16);
and
ar_vid = new Video(320, 480);
ar_cam = Camera.getCamera();
with
var ar_vid:Video = new Video(320, 480);
var ar_cam:Camera = Camera.getCamera(); //I don't know if Camera is right after the : so you could use * if that doesn't work
In actionscript 3 the syntax is as follows:
var [nameOfObject]:[typeOfObject] = new [ObjectClass](params);
Good luck
I'm able to load graphics from an external library with no problems, but for some reason all of the audio will not load/play.
Here's the loader class I'm using...
package
{
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.events.Event;
import flash.net.URLRequest;
import flash.text.Font;
public class LoadLibrary extends MovieClip
{
private var gear:MovieClip = new mcGear();
private var txtLoading:BlankClip;
private var _gameLib:String = "";
private var _Impact:Font = new Impact();
public function LoadLibrary(gameLibrary:String)
{
_gameLib = gameLibrary;
addChild(gear);
gear.x = 512;
gear.y = 384;
gear.alpha = .2;
gear.scaleX = .33;
gear.scaleY = .33;
txtLoading = new BlankClip(_Impact, "LOADING...", -400, -60, 800, 120, 26, "center", 5);
addChild(txtLoading);
txtLoading.x = 512;
txtLoading.y = 525;
txtLoading.alpha = .2;
var request:URLRequest = new URLRequest(_gameLib);
LoadVars.LIBLOADER.contentLoaderInfo.addEventListener(Event.COMPLETE, gameLibraryLoaded);
LoadVars.LIBLOADER.load(request);
}
private function gameLibraryLoaded(e:Event):void
{
removeChild(gear);
removeChild(txtLoading);
LoadVars.LIBLOADER.contentLoaderInfo.removeEventListener(Event.COMPLETE, gameLibraryLoaded);
var loaderInfo:LoaderInfo = LoaderInfo(e.currentTarget);
LoadVars.APPDOMAIN = loaderInfo.applicationDomain;
dispatchEvent(new GameEvents(GameEvents.LIBRARY_LOADED));
}
}
}
and the functions in my main class...
private function loadLib():void
{
_loadGraphics = new LoadLibrary("Elemental_Library.swf");
addChild(_loadGraphics);
_loadGraphics.addEventListener(GameEvents.LIBRARY_LOADED, test);
}
private function test(e:GameEvents):void
{
trace("LOADED");
var music:Sound = new GameMusic();
music.play();
}
Everything works fine until I try music.play and I get "1180: Call to a possibly undefined method GameMusic." I've tried several other audio clips and I get the same message. I tried creating a new library and imported just one audio file, same message. I verified I'm using the correct linkage names and the crazy part is that all of the movie clips load just fine from the same library.
Changed test to...
private function test(e:GameEvents):void
{
trace("LOADED");
var musicClass:Class = Class(LoadVars.APPDOMAIN.getDefinition("GameMusic"));
var music:Sound = Sound(new musicClass()); music.play();
}
I knew it was something stupid :P
I've searched a lot but nothing seems working for me. Assistance of somebody is very much appreciated in this regard. Thanks a lot. I'm new to AS3. I'm using FlashDevelop. Below is the code I used,
package
{
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;
import flash.net.URLRequest;
import flash.events.MouseEvent;
import flash.utils.ByteArray;
import flash.net.FileReference;
import com.adobe.images.JPGEncoder;
import flash.geom.Rectangle;
public class Main extends Sprite
{
private var modelBmp : BitmapData;
private var alphaBmp : BitmapData;
private var destPoint : Point = new Point(0, 0);
private var mask1:Loader = new Loader();
private var mask2:Loader = new Loader();
private var f:Bitmap;
private var fileReference:FileReference = new FileReference();
private var movie:MovieClip = new MovieClip();
private var loadedimage:Bitmap;
private var loadedimage1:Bitmap;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
if (loadAssets()) {
trace('merge loaded');
modelBmp = new BitmapData(loadedimage.width, loadedimage.height);
modelBmp.draw(loadedimage);
alphaBmp = new BitmapData(loadedimage1.width, loadedimage1.height);
alphaBmp.draw(loadedimage1);
var rect:Rectangle = new Rectangle(0, 0, 200, 200);
var pt:Point = new Point(20, 20);
var mult:uint = 0x80; // 50%
modelBmp.merge(alphaBmp, rect, pt, mult, mult, mult, mult);
var bm1:Bitmap = new Bitmap(modelBmp);
addChild(bm1);
bm1.x = 400;
var bm2:Bitmap = new Bitmap(alphaBmp);
addChild(bm2);
bm2.x = 200;}
}
private function loadAssets():void
{
mask2.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete1);
mask1.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
mask2.load(new URLRequest("Photo.png"));
mask1.load(new URLRequest("back.png"));
trace('asset loaded');
}
private function loadComplete(event:Event):void
{
loadedimage = Bitmap(mask1.content)
var bitmap:BitmapData = new BitmapData(loadedimage.width, loadedimage.height, false, 0xffffffff);
bitmap.draw(loadedimage, new Matrix())
var image:Bitmap = new Bitmap(bitmap);
//addChild(image);
trace('image1 loaded');
}
private function loadComplete1(event:Event):void
{
loadedimage1 = Bitmap(mask2.content)
var bitmap:BitmapData = new BitmapData(loadedimage1.width, loadedimage1.height, false, 0xffffffff);
bitmap.draw(loadedimage1, new Matrix())
var image:Bitmap = new Bitmap(bitmap);
//addChild(image);
trace('image2 loaded');
}
}
}
How to use Bitmap.merge():
var bitMapData1:BitmapData = new BitmapData(100,100); //or embedded item
var bitMapData2:BitmapData = new BitmapData(100,100); // "
var bitmap:Bitmap = new Bitmap(bitMapData1);
this.addChild(bitmap);
bitmap.merge(bitMapData2, new Rectangle(0, 0, 100, 100), new Point(0, 0), 128, 128, 128, 128);
As others have noted, Flash is forbidden from creating, altering, modifying, saving or otherwise manipulating files. There are several ways of getting this data out of flash and into a technology that has these abilities (such as PHP), or you can use the flash.filesystem package in Air (as previously noted).
Hope that helps =
= update =
Your code is problematic in that you are writing your urlRequest and then acting upon the loaded content in one function. The URL request simply hasn't had time to fire, and the rest of your function fails, because Mask2.content == undefined or null... I'm surprised it doesn't throw an error.
Other than that, it looks like it should work.
Try this:
private var _mask1:Loader; // _lowerCase naming convention
//constructor... call init()
//init.. call loadAssets()
private function loadAssets():void
{
_mask1 = new Loader(); //generally not a good idea to create objects when declaring variable
_mask1.addEventListener(Event.COMPLETE, onCompleteFunction);
_mask1.load(new URLRequest("Dress04.png"));
private function onCompleteFunction(e:Event):void
{ ...
Note that since you are doing multiple loads, you will need to check if both are loaded before acting upon the loaded content. You can do this with a simple boolean check or... whatever. You might also check out something like LoaderMax, which has built in load queueing like this.
Note also that good asset loading usually involves a try...catch statement and the handling of several events - IOErrorEvent.IO_ERROR , for example.
= update 2 =
Okay - we're just getting into programming logic now.
This is a problem:
private function init(e:Event = null):void
{
if (loadAssets()) {
trace('merge loaded');
//...
//...
private function loadAssets():void
{...
You're essentially asking loadAssets() to a return a value, but its return type is void, and so will absolutely fail. Besides that, the loadAssets() is only instigating the loader, and not tracking whether the load was successful.
Lets break it into a few more steps, and set up a really simple loading queue:
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.URLRequest;
public class Main extends Sprite
{
private var modelBmp : BitmapData;
private var alphaBmp : BitmapData;
private var destPoint : Point;
private var mask : Loader;
private var f : Bitmap;
private var movie : MovieClip;
private var loadedImages: Array;
private var imageQueue : Array;
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
//initialize variables
private function init(e:Event = null):void
{
//just set up a simple queue of images to load
imageQueue = ['Photo.png', 'back.png'];
loadedImages = [];
destPoint = new Point(0, 0);
mask = new Loader();
movie = new MovieClip();
loadAsset( imageQueue[0] );
}
private function loadAsset(target:String):void
{
mask.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
mask.load(new URLRequest(target));
}
private function loadComplete(event:Event):void
{
loadedimage = Bitmap(mask.content);
var bitmap:BitmapData = new BitmapData(loadedimage.width, loadedimage.height, false, 0xffffffff);
bitmap.draw(loadedimage, new Matrix())
var image:Bitmap = new Bitmap(bitmap);
loadedImages.push(image);
mask.unload();
trace(imageQueue[0] + " loaded");
imageQueue.splice( 0, 1); //remove the first index
if (imageQueue.length > 0){
loadAsset(imageQueue[0]);
}else{
mergeImages(); //if the queue is empty, then merge
}
}
private function mergeImages():void
{
modelBmp = new BitmapData(Bitmap(loadedImages[0]).width, Bitmap(loadedImages[0]).height);
modelBmp.draw(loadedimage);
alphaBmp = new BitmapData(Bitmap(loadedImages[1]).width, Bitmap(loadedImages[1]).height);
alphaBmp.draw(loadedimage1);
var rect:Rectangle = new Rectangle(0, 0, 200, 200);
var pt:Point = new Point(20, 20);
var mult:uint = 0x80; // 50%
modelBmp.merge(alphaBmp, rect, pt, mult, mult, mult, mult);
var bm1:Bitmap = new Bitmap(load);
addChild(bm1);
bm1.x = 400;
var bm2:Bitmap = new Bitmap(alphaBmp);
addChild(bm2);
bm2.x = 200;}
}
}
I haven't checked to see if this works, so it might take a little messing with, the but basic idea should work for you. There are a bunch of ways to deal with chained conditional asset loading, this is a simple example.
Hope that helps -
This might seem a bit on the nose, but you can use the merge() method of the BitmapData class to merge two bitmaps images into one. There's an example using the merge() method at those links.
As far as saving to a local disk goes, Flash Player allows access to the file system using the FileReference class. The FileReference class has the save() method, which prompts the user to browse for a location on their file system.
For Air applications, you can access the file system by using the classes in the flash.filesystem package.