Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




Type Casting To A Class Name



I'm trying to type cast an item in an array (inventoryList) to a Class, so I can addChild the movieClip to the stage. The items in the inventory 'carrotIcon and passportIcon' - I also have movieClips of the same name in the library with their own classes.

It works when I just change the line to 'addIconName = new carrotIcon()' for example. Maybe the answer is that I should use something else than 'Class' as the type cast. I've tried MovieClip to no avail.

var itemName:*;
var inventoryList:Array = new Array();
inventoryList.push("carrotIcon");
inventoryList.push("passportIcon");

for (var i:int = 0; i < (inventoryList.length); i++)
{
itemName = Class(inventoryList[i]); //this is the line I'm having problems.
addIconName = new itemName();
addChild(addIconName);
}

Thanks for looking!
Joe



FlashKit > Flash Help > Actionscript 3.0
Posted on: 06-21-2008, 07:29 AM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Type Casting
I have an input box where I want to put a number value that begins with zero. "016" I then put this value into an array and it drops the zero. I want the number value to be treated like a string. I have tried using the myText.toString() function, and the String(myText) constructor, but it still takes off the zero at the begining. does anyone have any ideas, or has anyone experienced this before?

Type Casting
Is there any way to convert String to Number? Flash doesn't convert it automaticly in my code. I used .valueOf but I didn't work.

Type Casting Problem
Hello gurus,
I have a problem:
while loading a number from a variable in a text file, into a script, i found that the number is not really a number but a string or a character. But i need it as a number to perform some operation. Can you please help me on how to convert that??

Type Casting Problems
Quick Rundown of What I am doing so you can understand the logic is:

Building multipage Form In first Frame I hove no movies just initialized a bunch of Variables to store Data filled in from Forms on various Pages (frames 2 thru 7)
Page/Frame 2 is First Page which asks for Basic Details like Name Phone #s etc

I have a function that checks (when next page button is clicked) that checks Page form inputs are all filled correctly and if so updates the Variables (from frame 1) with the entered Data. Then on Return to the Page I prefill fields from the stored Variables.

Now the Problem:

For 4 different Phone numbers on the Page I have 3 inputs each (AreaCode, Prefix, Suffix)

When I go to store the entered values to 1 Variable each (Frame one/ Variable of type int/ to store the 10 digit number before sending to php serverside script) I concat the 3 input fields for each number and cast to int then on reenter page to preload the values again I cast the 10 digit int back to string and do a substr to divide them up and put them in the inputs as text.

However weird things happen Company Phone and Personal phone seem to usually work fine but Cell Phone and Fax get all muffed up the first time I renter (after leaving and returning they stay the same as first muffed up appearance)

Here is the portions relating to the Events please advise if you have any ideas how I can stop this behaviour. Thanks

Setting the Variable before leaving page

PHP Code:



cphone = int(CompanyPhoneAC.text + CompanyPhonePF.text + CompanyPhoneSF.text);
cfax= int(CompanyFaxAC.text + CompanyFaxPF.text + CompanyFaxSF.text);
pphone = int(PersPhoneAC.text + PersPhonePF.text + PersPhoneSF.text);
pcell = int(PersCellAC.text + PersCellPF.text + PersCellSF.text);




Setting the Inputs when Returning to Page

PHP Code:



var PersCAC:String = String(pcell);
PersCAC = PersCAC.substr(0,3);
if(PersCAC.length<3){
    PersCAC = "" ;}
PersCellAC.text  =  PersCAC;

var PersCPF:String = String(pcell);
PersCPF = PersCPF.substr(3,3);
if(PersCPF.length<3){
    PersCPF = "";}
PersCellPF.text  =  PersCPF;

var PersCSF:String = String(pcell);
PersCSF = PersCSF.substr(6,4);
if(PersCSF.length<4){
    PersCSF = "";}
PersCellSF.text  =  PersCSF;

var PersPAC:String = String(pphone);
PersPAC = PersPAC.substr(0,3);
if(PersPAC.length<3){
    PersPAC = "";}
PersPhoneAC.text  =  PersPAC;

var PersPPF:String = String(pphone);
PersPPF = PersPPF.substr(3,3);
if(PersPPF.length<3){
    PersPPF = "";}
PersPhonePF.text  =  PersPPF;

var PersPSF:String = String(pphone);
PersPSF = PersPSF.substr(6,4);
if(PersPSF.length<4){
    PersPSF = "";}
PersPhoneSF.text  =  PersPSF;

var CompanyPAC:String = String(cphone);
CompanyPAC = CompanyPAC.substr(0,3);
if(CompanyPAC.length<3){
    CompanyPAC = "";}
CompanyPhoneAC.text  =  CompanyPAC;

var CompanyPPF:String = String(cphone);
CompanyPPF = CompanyPPF.substr(3,3);
if(CompanyPPF.length<3){
    CompanyPPF = "";}
CompanyPhonePF.text  =  CompanyPPF;

var CompanyPSF:String = String(cphone);
CompanyPSF = CompanyPSF.substr(6,4);
if(CompanyPSF.length<4){
    CompanyPSF = "";}
CompanyPhoneSF.text  =  CompanyPSF;

var CompanyFAC:String = String(cfax);
CompanyFAC = CompanyFAC.substr(0,3);
if(CompanyFAC.length<3){
    CompanyFAC = "";}
CompanyFaxAC.text  =  CompanyFAC;

var CompanyFPF:String = String(cfax);
CompanyFPF = CompanyFPF.substr(3,3);
if(CompanyFPF.length<3){
    CompanyFPF = "";}
CompanyFaxPF.text  =  CompanyFPF;

var CompanyFSF:String = String(cfax);
CompanyFSF = CompanyFSF.substr(6,4);
if(CompanyFSF.length<4){
    CompanyFSF = "";}
CompanyFaxSF.text  =  CompanyFSF;

Dynamic Type Casting - Is It Possible?
Is there a way to do something like the following...?


Code:
var myClass:String = "blah";
var inst = new[myClass]();
I've invented the above syntax--though I'd be delighted if it turned out to work! For clarity, I would hope for something like the above code to be synonymous with the following:


Code:
var inst:blah = new blah();
...So is it possible to dynamically specify a class name when creating a new instance?

Type Casting Classes
Alright let's say I have a MovieClip in the library with the linkage set to TestClass and I have this code...

var string1:String = "Test";
var string2:String = "Class";

var testClass:* = new Class([string1 + string2])();
this.addChild(testClass);

so testClass should be an instance of TestClass, this works for me sometimes and sometimes it doesn't.

Does any one have any advice as a better way to do this, and what this tecnique is called ( root["string" + "1"])?

Thanks for all you guy's help!

Type Casting And Equality
TypeError: Error #1034: Type Coercion failed: cannot convert uk.co.andrewrea.brickwall::BrickWall@24b1191 to uk.co.andrewrea.brickwall.BrickWall.

Does anyone know why this would be. I create a variable of Type BrickWall and then assign it a variable of type BrickWall the event data of the loader i.e.


ActionScript Code:
wall = e.target.content.wall;

both wall and e.target.content.wall are of the same type of the same package, but seem to be handled as different types. Anyone know why this is?

Thanks,

Andrew

How Strong Is Type Casting
I have a variable saved in the first frame of my fla file
var question:Number = 0;


I want to make it possible for sombody to jump around in the exersice so I built kind of a jumper and saved it in its own mc. In the mc I have a button called jump with the following code.

_root.question = q.text;

Now that question will work but when I tried to add one to my question variable it did something weird. Say I want to jump to question 2. When it tries to add one to my question variable I get 21. It seems that by saving q.text to my question variable, it gets recasted to a String. Has anybody else bumped into this problem.

Side note: I did fix this with parseInt. I am just curious why this happened in the first place, is type casting really not that strong?

Dynamic Type Casting - Is It Possible?
Is there a way to dynamically typecast a new instance? Maybe something like the following...?


Code:
var myClass:String = "blah";
var inst = new[myClass]();
I've invented the above syntax--though I'd be delighted if it turned out to work! For clarity, I would hope for something like the above code to be synonymous with the following:


Code:
var inst:blah = new blah();
...So is it possible to dynamically specify a class name when creating a new instance?

AS2 - Casting An Object To A Different Type
Hi all,
I'm trying to convert a String to Slide (mx.screens.Slide). Everytime I'm getting null.


ActionScript Code:
var slide = "slide_11"
_root.presentation.gotoSlide(slide);


I need to do this but it doesn't work. I have a string because slide_11 was in a xml file.

Any idea?

Help: Casting String Gotten From Xml To A Number Type
Hi all,

I have a major problem, I have parsed the data from an xml doc to global vars in flash and need to use a few of them as numbers for things the position of "nodes" on the screen. However I can not cast the data stored as a var to a number or int value.

For example in the code below when the set Node button is pressed it traces the "Node's" current X value, then the value in the global var gotten from the xml, which contains the x position of where to place the Node.

Next it creates a new var of Number Type and assigns it the Number value of the string in global var.

It then traces the new value of SNtopLeftX and sets the x pos of the Node's movie clip to the value of SNtopLeftX

However the Node doesn't move and this is the output I get from the traces

Start Node is at x = -734.5
nod_topLeftX is 16
TopLeftX = 16
SN TopLeftX = NaN

I do not understand why I am getting NaN when the string of nod_topLefX is 16, any ides?
-------------------------------------------------------------------------------------------------------------------







Attach Code

butNodeSet.onRelease = function() {

trace ("Start Node is at x = " + mcStartNode._x);
trace ("nod_topLeftX is " + nod_topLeftX);

var SNtopLeftX:Number = Number(nod_TopLeftX);
trace ("StartNode TopLeftX = " + SNtopLeftX);
mcStartNode._x = SNtopLeftX;
}

Help: Casting String Gotten From Xml To A Number Type
Hi all,

I have a major problem, I have parsed the data from an xml doc to global vars in flash and need to use a few of them as numbers for things the position of "nodes" on the screen. However I can not cast the data stored as a var to a number or int value.

For example in the code below when the set Node button is pressed it traces the "Node's" current X value, then the value in the global var gotten from the xml, which contains the x position of where to place the Node.

Next it creates a new var of Number Type and assigns it the Number value of the string in global var.

It then traces the new value of SNtopLeftX and sets the x pos of the Node's movie clip to the value of SNtopLeftX

However the Node doesn't move and this is the output I get from the traces

Start Node is at x = -734.5
nod_topLeftX is 16
TopLeftX = 16
SN TopLeftX = NaN

I do not understand why I am getting NaN when the string of nod_topLefX is 16, any ideas?


------------------------------------------------------------------------------------------------------------------- This is my Code
butNodeSet.onRelease = function() {

trace ("Start Node is at x = " + mcStartNode._x);
trace ("nod_topLeftX is " + nod_topLeftX);

var SNtopLeftX:Number = Number(nod_TopLeftX);
trace ("StartNode TopLeftX = " + SNtopLeftX);
mcStartNode._x = SNtopLeftX;
}

Instantiation/Type Casting Problem With GetChildAt
Alrighty so I'm kinda new with actionscript 3.0 and have been having a problem with getChildAt. I'm working on creating a dynamic menu have have found that when I addChildAt using a for loop it adds all the childs properly however when I go to use getChildAt on the MovieClip that I have created using "var newMC:MovieClip = mc_container.getChildAt(x)" it returns a problem saying "Implicit coercion of a value with static type flash.display:DisplayObject to a possible unrelated type flash.display:MovieClip"
Anyways I'm trying to get it to work however I found a work around that I'm not sure why works where I just do "var newMC = mc_container.getChildAt(x)" and that will let me access all of the variables and stuff however when I do a trace on the newMC it says type undefined... Anyways some help would be awsome, and heres my code btw, should be pretty easy to read.


import flash.display.MovieClip;
import flash.display.Shape;

var news_content_num = 1;
var news_padding = 0;
var news_padding_distance = 10;

var news_ymin = 0;

var news_full_width = 289;
var news_full_height = 154;

var news_compact_height = 61;

var news_shading_xval = 290;
var news_shading_yval = 255;

var news_bordersize = 1;
var news_shading_offset = 1;

var news_content:MovieClip = new MovieClip();

function drawBorder():Shape {
var border:Shape = new Shape();
border.name = "border_"+[x];

//Add the Left Line and then Top Line
border.graphics.lineStyle(news_bordersize, 0xCCCCCC, 1);
border.graphics.moveTo(0, news_ymin + news_full_height);
border.graphics.lineTo(0, news_ymin);
border.graphics.lineTo(news_full_width, news_ymin);

//Add the Right Side Drop Shadow
border.graphics.lineStyle(news_bordersize, 0X999999);
border.graphics.moveTo(news_full_width+1, news_ymin+2);
border.graphics.lineTo(news_full_width+1, news_full_height+news_shading_offset);

//Add the Bottom Side Drop Shadow
border.graphics.lineTo(2, news_full_height+news_shading_offset);
//this.addChild(border);

//Add the Right Side Border
border.graphics.lineStyle(news_bordersize, 0X000000);
border.graphics.moveTo(news_full_width,news_ymin);
border.graphics.lineTo(news_full_width, news_full_height);
//this.addChild(border);

//Add The Bottom Side Border
border.graphics.lineTo(0, news_full_height);

return border;
}

function drawNews_fullSize(x:Number) {
var mc = new MovieClip();
mc.name = "news_"+[x];
mc.y = news_padding;
mc.addChild(drawBorder());
news_content.addChildAt(mc, x);
}

function set_padding()
{
news_padding = news_padding + news_full_height + news_padding_distance;
}

for(x = 0; x < 4; x++){
drawNews_fullSize(x);
set_padding();
}

this.addChild(news_content);

//What I want it to run as...
//var news:MovieClip = news_content.getChildAt(0);
//What currently works...
//var news = news_content.getChildAt(0);

Draggable MC, Class & Casting
Let’s say I wish to drag a panel but only from a strip at the top. I put a MovieClip named mcBar inside a MovieClip named mcPanel.
When I code frame one in the timeline it works.


ActionScript Code:
mcPanel.mcBar.addEventListener(MouseEvent.MOUSE_DOWN, downHandle);  mcPanel.mcBar.addEventListener(MouseEvent.MOUSE_UP, upHandle);     function downHandle(evtObj:MouseEvent):void{                                    this.startDrag();                    }     function upHandle(evtObj:MouseEvent):void{                                    this.stopDrag();                    }



What’s confusing is that it works. Why is the whole thing dragging? I’m assuming it’s event propagation? mcBar’s mouse down is “bubbling” to mcPanel… Even though this is exactly what I want – Don’t completely understand it.


Now, further complication is when I move the code to a class.


ActionScript Code:
package{        //imports    import flash.display.MovieClip;    import flash.events.MouseEvent;            public class DraggableClip extends MovieClip{                //constructor        public function DraggableClip(){                        this.addEventListener(MouseEvent.MOUSE_DOWN, downHandler);            this.addEventListener(MouseEvent.MOUSE_UP, upHandler);        }                //methods        function downHandle(evtObj:MouseEvent):void{                parent.startDrag();        }        function upHandle(evtObj:MouseEvent):void{                parent.stopDrag();            }    }}


Now, if I assign mcBar via Linkage to DraggableClip.as, only the bar drags. This is the behavior I would have expected when I initially coded the timeline. However, I really do want the entire panel to drag so how do I target it?

As the target for the drag methods:


this refers to the instance of the class(mcBar only) , parent throws a 1061: Call to a possibly undefined method startDrag through a reference with static type flash.displayisplayObjectContainer. error.

I found a drag MC sample from Jen deHaan that had: var thisMC:MovieClip = event.currentTarget as MovieClip;

I barely understand that this is a Casting Operation...Is this what I'm missing?

In Summary:What do I need to do to get mcBar inside mcPanel to drag both mcBar and mcPanel from code in a class?
Also if my issue is with casting, why?
In my deHaan sample, why legacy as operator vs type(expression)?
Thanks for any/all insight.

Casting A Base Or Inherited Class?
Howdy Folks,

I have a number of movieclips on stage. Each of these movieclips has their base class assigned to a generic Character class which gets populated with specific data for each character via an xml file.

When the time comes to generate the next screen i would like to cast the chosen movieclips base Character class back into another Character class but am not exactly sure how that would be done.

So in the interim I have a function that creates a new Character object and walks through properties of the chosen movieclip and assigns them...

Is it possible to cast a base class of a movieclip back into another class without inheriting all the movieclip properties that I don't need?

many thanks,

frank grimes

Class Casting Strange Behavior
So, I have a class named Node, and several classes named ProjectNode, UserNode, etc that extends Node. I also have a class named GraphNode with a member variable of type Node (and some other stuff). Ideally, I'd like to be able to assign any subclass of Node to this variable, and retrieve the actual class (eg: UserNode) later by using a cast (because of some other variables/methods in Node, it's possible to determine what kind of Node it is using only methods of Node, and thus choose the correct class to cast).

However, when I try to do this, the cast from Node to UserNode fails, returning null.

Any thoughts on why this would be?

Casting Precomposed Movieclips On Stage To A Class
Hello,

I've got two movieclips on stage hourGlass and hourGlass2. The hourGlass movieclip is placed dynamically and has its class and base class linkage setup. When I place this on screen via code I can control it perfectly.

The other movieclip, hourGlass2, is placed directly onto the stage itself and for the life of me I cannot figure how to cast it to same class that the other movieclip uses. The instance name on the stage is called hourGlass2.

Is it possible to cast a movieclip, that was placed directly on the stage, to a class and then control it?

Here's the code I am using:

import com.grimes.testCase.HourGlass;

// Dynamically placed MovieClip (works fine)
var hourGlass:HourGlass;
hourGlass = new HourGlass(60);
hourGlass.x = 200;
hourGlass.y = 200;
addChild (hourGlass);
hourGlass.flipTheGlass();

// Drag and dropped MovieClip with hourGlass2 instance name (throws 1151: A conflict exists with definition hourGlass2 in namespace internal error)
var hourGlass2:HourGlass;
hourGlass2 = new HourGlass(30);
hourGlass2.flipTheGlass();

many thanks in advance,

frank grimes

Casting XML Node Text Back Into A Library Item Class
Hello,

In my library I have a movieclip called START_GAME_BTN that uses the same name for its class which is START_GAME_BTN.

The problem I am having is figuring out how to cast the node text for <clipName> which is START_GAME_BTN back into the item in my library.

The XML snippet looks like this:


Code:
<startGameButton>
<clipName>START_GAME_BTN</clipName>
<position>
<xpos>560</xpos>
<ypos>420</ypos>
</position>
</startGameButton>
In my class that is parsing the XML needed to derive the items necessary for screen display, I initally do this for the start game button:


Code:
private var _startGameBtn:MovieClip;
But this is wrong because it really needs to be cast like this:


Code:
private var _startGameBtn:START_GAME_BTN;
Unfortunately this is where I am a little stumped. I tried doing this:


Code:
_startGameBtn = _xmlScreenData.screen.startGameButton.clipName as MovieClip;
But when I ran through the debugger the value of _startGameBtn was still null. I then tried this:


Code:
var gameButton:String;
gameButton = _xmlScreenData.screen.startGameButton.clipName;
_startGameBtn = gameButton as MovieClip
Unfortunately _startGameBtn was still null.

It's almost like I need to do:


Code:
//
_startGameBtn:_xmlScreenData.screen.startGameButton.clipName as _xmlScreenData.screen.startGameButton.clipName
_startGameBtn = new _xmlScreenData.screen.startGameButton.clipName()
//
But I know this won't work...has anyone run into this problem before?

Any suggestions would be greatly appreciated.

cheers,

frank grimes

Casting LoaderInfo.content (.swf File) To Its Document Class Causes Compilel Err 1180
I have a Flash file (Foo.fla) with a document class Foo that has a movieclip in its library named Bar that is linked to a class Bar (generated bij Flash). The Foo constructor:


Code:
public function Foo() {
addChild(new Bar());
}
Foo.fla compiles to Foo.swf and runs with no errors. Now from a different Flash file (Test.fla) with a document class Test I want to load Foo.swf using the flash.display.Loader class:


Code:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoad);
loader.load(new URLRequest("Foo.swf"));
In the event handler I get a compile error for Foo.as (the document class for Foo.swf) when I try to cast the content property of the contentLoaderInfo object to an instance of Foo.


Code:
private function onLoad(e:Event):void {
var loaderInfo:LoaderInfo = e.target as LoaderInfo;
loaderInfo.content as Foo; // Cause a compile error in Foo.as
}

Quote:




Foo.as, Line 6
1180: Call to a possibly undefined method ProgressBar.
addChild(new Bar());




Foo.as compiles without errors but Test.as causes a compile error in Foo.as which is unexpected.

Why is this happening and what can I do to prevent it?

Thank you!

Class Constants Type
Hi,

I'm just being curious...

Everywhere in AS3 those constants used are string values. E.g.

ActionScript Code:
StageScaleMode.NO_SCALE : String = "noScale"
What I've seen when I worked with JAVA for a while, those things would be rather instances of the StageScaleMode whereas the class would look like
ActionScript Code:
// somethig somethingpublic static const NO_SCALE : StageScaleMode = new StageScaleMode ( 'noScale' )public function StageScaleMode ( type : String ){    this.type = type;}public var type : String;

Is there any reason for this apart from the possibility to set the value by yourself as stage.scaleMode = "noScale"; ?

Get The Class Type Of An Object
Say I created an object like this:

var p = new BasketBall();

I want to access a certain property of p, such that it would return "BasketBall" or anytihng to indicate for me the class type. Is that possible?

Thanks

Fancy Box Type Moving Graphic Type Cool Efect But Im To Dumb Type Thingy
i am tring to make a box thinky simaler to the one on www.starvingeyes.com but cant even work out how to start it. is there anyone who can point me in the right direction or to a tutorial ?

the box has a graphic inside a grided box the sections of the graphic fade in and out as the mouse goes over them and displays random sections when the user is not moving the mouse over the box

i did find java tutorials for this effect but would much preffer it to come from flash as java is a bugger to get working on some machines

Any way thanks in advance for any help

Steven Green one_mad_punk@yahoo.co.uk

Question About Arrays Of Type Class
ok i have a class "Student" and i want to create an array of students... i have a constructor for the class Student that takes in all the variables and sets them correctly (so if i type something like Student(001,"Nate",12,"haha") it will set the variables.

now to create the array i think i should use code: var myarrayname:Array = new Array();

but where do i tell the array that it should act like a Student???

Also when i am adding information to the array (it reads in from a file) should i just call something like
code: myarrayname[i](001,"nate",12,"haha");? because i dont know if that is right also


lastly are arrays autoresizing? or do i need to tell it how big to be at some point?

sorry about so many basic questions...

Return Objects Class Type
How can i return an objects class type. If i have a class

Code:
class test {
//some code
}
how could i then trace or somehow return the value "test" for any of my object. For example:

Code:
var myTest:test = new test();
trace(myTest._classtype);

Type Convertion From String To Class
How do i convert String Type to Class..
I wish to dynamically create a new instance of a class.

eg.
If i have a sring "className1"
how to create a new instance by -> new className1()

thx in advance
Angel

Passing A Class Type And Declare It
i am trying to pass a class type into a function which then declares it to an array this way:

i have this class which i am using the add movieclips form the library.

PHP Code:



package {
    import flash.display.MovieClip;
    
    public class TestClass extends MovieClip {
        
        private var allTypes:Array;
        
        public function TestClass {
            allTypes = new Array();
        }
        
        public function addType(i:Number, type:*) {
            //then i wanna declare the type of the class that is put into this method
            allTypes[i] = new type("name", 10, 50);
            addChild(allTypes[i]);
        }
    }





and then on my main timeline, i have this document class, which will have an instance of the TestClass, and add in types which i want to add onto the stage. i wish to pass in the type of the class name of the exported movieclips which i have in my libraries.

PHP Code:



package {
    import flash.display.MovieClip;
    import TestClass;
    
    public function MainMovie extends MovieClip {
        
        var TestClass:TestClass;
        
        public function MainMovie() {
            TestClass = new TestClass();
            //now i want to add the Type of the class into the paramaters
            //these types are class names of the movieclips in the library that are exported for actionscript in linkage
            TestClass.addType(0, Plane);
            TestClass.addType(1, Bird);
        }
    }





however, this doesn't seem to work. any idea how should the syntax or the right way be for doing this?
thanks.

Error With Numbnail Type Class
Hey all.. I'm making a thumbnail type class here and it's working just fine, but the problem comes when I want to rollover/ rolloff my thumbs. SOMETIMES I get this error when I roll off the thumb:

TypeError: Error #1006: setTextFormat is not a function.
at com.mysite.testing::CreateThumbs/::boxOnMouseOut()

Any thoughts?


Code:
package com.mysite.testing {

import flash.display.Sprite;
import flash.events.*;
import flash.display.MovieClip;
import flash.text.TextFormatAlign;
import flash.text.TextField;
import flash.text.TextFormat;
import fl.containers.UILoader;

public class CreateThumbs extends Sprite{

private var _urlString:String; //url for product
private var _imgString:String; //url for image
private var _titleString:String; //title of product
private var _catString:String; // category id
private var graceArray:Array = new Array();
private var thumbHider:MovieClip = new MovieClip();

public function CreateThumbs(newPos:Number, thumbXML:XML) {

var dataLoader:MovieClip = new MovieClip();
dataLoader.graphics.lineStyle(1, 0xffffff, 1, true);
dataLoader.graphics.beginFill(0x5d5d5d, 1);
dataLoader.graphics.drawRect(-1, -1, 112, 152);
dataLoader.graphics.endFill();
dataLoader.x = newPos + 30;
dataLoader.y = 45;
dataLoader.mouseEnabled = true;
dataLoader.height = 160;
dataLoader.width = 120;
dataLoader.buttonMode = true;
dataLoader.addEventListener(MouseEvent.MOUSE_OVER, boxOnMouseOver);
dataLoader.addEventListener(MouseEvent.MOUSE_OUT, boxOnMouseOut);
dataLoader.addEventListener(MouseEvent.MOUSE_DOWN, boxOnPress);

var photoLoader:UILoader = new UILoader();
photoLoader.mouseEnabled = true;
photoLoader.width = 110;
photoLoader.height = 150;
photoLoader.y = 0;
photoLoader.x = 0;
photoLoader.source = thumbXML.thumbnailUrl.text(); //substitute with url to 150x110 image

thumbHider.graphics.lineStyle(0, 0xa9a9a9, 0, true);
thumbHider.graphics.beginFill(0x000000, 1);
thumbHider.alpha = .6;
thumbHider.graphics.drawRect(-1, -1, 110, 150);
thumbHider.graphics.endFill();
thumbHider.x = 0;
thumbHider.y = 0;
thumbHider.mouseEnabled = true;
thumbHider.height = 153;
thumbHider.width = 112;
thumbHider.buttonMode = true;

var textHolder:MovieClip = new MovieClip();
textHolder.graphics.drawRect(1, 1, 111.5, 25);
textHolder.x = -2;
textHolder.y = 151;

var boxName:TextField = new TextField();
boxName.text = thumbXML.title.text();
boxName.y = 5;
boxName.width = 110;
boxName.height = 20;
boxName.mouseEnabled = false;
boxName.wordWrap = true;
boxName.textColor = 0xffffff;
boxName.antiAliasType = "advanced";

var boxNameFormat:TextFormat = new TextFormat("Trebuchet MS", 11, 0xffffff, false, null, null, null, null, TextFormatAlign.CENTER);
boxName.setTextFormat(boxNameFormat);
textHolder.addChild(boxName);
dataLoader.addChild(textHolder);
dataLoader.addChild(photoLoader);
dataLoader.addChild(thumbHider);
addChild(dataLoader);
}

private function boxOnMouseOver(evt:MouseEvent){
thumbHider.alpha = 0;

evt.target.parent.graphics.clear();
evt.target.parent.graphics.lineStyle(2, 0xffffff, 1, true);
evt.target.parent.graphics.drawRect(-1, -1, 112, 152);
var bNFormat:TextFormat = new TextFormat("Trebuchet MS", 11, 0xffffff, true, null, null, null, null, TextFormatAlign.CENTER);
evt.target.parent.getChildAt(0).getChildAt(0).setTextFormat(bNFormat);

}

private function boxOnMouseOut(evt:MouseEvent){
thumbHider.alpha = .4;
evt.target.parent.graphics.clear();
evt.target.parent.graphics.lineStyle(1, 0xffffff, 1, true);
evt.target.parent.graphics.drawRect(-1, -1, 112, 152);
var bNFormat:TextFormat = new TextFormat("Trebuchet MS", 11, 0xffffff, false, null, null, null, null, TextFormatAlign.CENTER);
evt.target.parent.getChildAt(0).getChildAt(0).setTextFormat(bNFormat);
}

private function boxOnPress(evt:MouseEvent){
//nothing yet
}

private function randomNumber(low:Number=NaN, high:Number=NaN):Number{
var low:Number = low;
var high:Number = high;

if(isNaN(low))
{
throw new Error("low must be defined");
}
if(isNaN(high))
{
throw new Error("high must be defined");
}
return Math.round(Math.random() * (high - low)) + low;
}
}
}

How To Code Class With Variable Type
I'm not really sure how to ask this question, but here it goes:

I want to define a class that works like this:


ActionScript Code:
class myTag {
 
public var tagName:String;
public var tagType:String;
public var tagContent:????
 
public function myTag(p_name:String, p_content:????) {
this.tagName=p_name;
if (typeof(p_content)=="string") {
this.tagType="string";
this.tagContent=p_content;
} else if (p_content.length!=undefined) {
this.tagType="collection";
var tagList=new Array();
for (var i in p_content) {
tagList.push(new myTag(p_content[i]));
}
this.tagContent=tagList;
} else if {p_content.tagType!=undefined) {
this.tagType="tag";
this.tagContent=p_content;
}
}
}


Is there a better way to do this without creating three separate classes?

In short, I guess what I need to know is:
is there a way to declare the type of a variable (like tagContent) in the constructor?

Any help/input would be greatly appreciated. Thanks in advance,
jase

Return Custom Objects Class Type
Hi Guys,

just wondering if someone could help me with this.

I create Mc's of class multiStops.City

they are stored in an Mc instanceName: container

I want to loop through my container and find all the mc's that are an instance of my custom City class.

I was trying this:


Code:
for (var obj:String in container) {
var b:Object = container[obj];
trace(b instanceof multiStops.City);
}
But it doesnt work. I get all false although I know they are some in there.
Is the way i use instanceof correct?

Maybe there is a better way?

I thought of setting a var in each of the objects var ofTypeCity:Boolean = true .. but I am sure there must be a native way???

Thanks

Mani

[Flash Shooter]Class Type Mismatch
I'm streamlining the code for this flash prototype from gotoandplay.it.
I haven't had any trouble until it recently is saying that my enemy call is type mismatch and I have no idea why?

Could someone take a look at my code and give me an idea what I might be doing wrong?

Link to zipped flash file.
http://www.filesend.net/download.php...94e62c539935ff

Can I Pass A Class Type As A Function Parameter?
So, in AS2, I had a function that would create different movieclips based on variables I passed in (because attachMovie() took the name of the movieclip as a string - e.g. attachMovie("man",...) or attachMovie ("car"...)).

In AS3, it's done more correctly now, with a var mc = new Man() or new Car().

Is there a way for me to pass the class type (Man or Car) as a function parameter to a function:

e.g.

public function MakeMovieClip(classType:<something>):MovieClip {
return new classType();
}

or do I need to basically make a giant switch/case block that switches based on strings (which is what I'm currently doing)?


Thanks,

--
Ken

Error 1006 And Thumbnail Type Class
Hey all.. I'm making a thumbnail type class here and it's working just fine, but the problem comes when I want to rollover/ rolloff my thumbs. SOMETIMES I get this error when I roll off the thumb:

TypeError: Error #1006: setTextFormat is not a function.
at com.mysite.testing::CreateThumbs/::boxOnMouseOut()

Any thoughts?

Code:

package com.mysite.testing {
   
   import flash.display.Sprite;
   import flash.events.*;
   import flash.display.MovieClip;
   import flash.text.TextFormatAlign;
   import flash.text.TextField;
   import flash.text.TextFormat;
   import fl.containers.UILoader;
   
   public class CreateThumbs extends Sprite{
      
      private var _urlString:String; //url for product
      private var _imgString:String; //url for image
      private var _titleString:String; //title of product
      private var _catString:String; // category id
      private var graceArray:Array = new Array();
      private var thumbHider:MovieClip = new MovieClip();
      
        public function CreateThumbs(newPos:Number, thumbXML:XML) {
                  
         var dataLoader:MovieClip = new MovieClip();
         dataLoader.graphics.lineStyle(1, 0xffffff, 1, true);
         dataLoader.graphics.beginFill(0x5d5d5d, 1);
         dataLoader.graphics.drawRect(-1, -1, 112, 152);
         dataLoader.graphics.endFill();
         dataLoader.x = newPos + 30;//*j;
         dataLoader.y = 45;
         dataLoader.mouseEnabled = true;
         dataLoader.height = 160;
         dataLoader.width = 120;
         dataLoader.buttonMode = true;         
         dataLoader.addEventListener(MouseEvent.MOUSE_OVER, boxOnMouseOver);
         dataLoader.addEventListener(MouseEvent.MOUSE_OUT, boxOnMouseOut);
         dataLoader.addEventListener(MouseEvent.MOUSE_DOWN, boxOnPress);
               
         var photoLoader:UILoader = new UILoader();
         photoLoader.mouseEnabled = true;
         photoLoader.width = 110;
         photoLoader.height = 150;
         photoLoader.y = 0;
         photoLoader.x = 0;
         photoLoader.source = thumbXML.thumbnailUrl.text(); //substitute with url to 150x110 image
         
         thumbHider.graphics.lineStyle(0, 0xa9a9a9, 0, true);
         thumbHider.graphics.beginFill(0x000000, 1);
         thumbHider.alpha = .6;
         thumbHider.graphics.drawRect(-1, -1, 110, 150);
         thumbHider.graphics.endFill();
         thumbHider.x = 0;//*j;
         thumbHider.y = 0;
         thumbHider.mouseEnabled = true;
         thumbHider.height = 153;
         thumbHider.width = 112;
         thumbHider.buttonMode = true;
         
         var textHolder:MovieClip = new MovieClip();
         textHolder.graphics.drawRect(1, 1, 111.5, 25);
         textHolder.x = -2;
         textHolder.y = 151;
      
         var boxName:TextField = new TextField();
         boxName.text = thumbXML.title.text();
         boxName.y = 5;
         boxName.width = 110;
         boxName.height = 20;         
         boxName.mouseEnabled = false;
         boxName.wordWrap = true;
         boxName.textColor = 0xffffff;
         boxName.antiAliasType = "advanced";
         
         var boxNameFormat:TextFormat = new TextFormat("Trebuchet MS", 11, 0xffffff, false, null, null, null, null, TextFormatAlign.CENTER);
         boxName.setTextFormat(boxNameFormat);
         textHolder.addChild(boxName);
         dataLoader.addChild(textHolder);
         dataLoader.addChild(photoLoader);
         dataLoader.addChild(thumbHider);
         addChild(dataLoader);
        }
      
      private function boxOnMouseOver(evt:MouseEvent){
         thumbHider.alpha = 0;
         
         evt.target.parent.graphics.clear();
         evt.target.parent.graphics.lineStyle(2, 0xffffff, 1, true);
         evt.target.parent.graphics.drawRect(-1, -1, 112, 152);
         var bNFormat:TextFormat = new TextFormat("Trebuchet MS", 11, 0xffffff, true, null, null, null, null, TextFormatAlign.CENTER);
         evt.target.parent.getChildAt(0).getChildAt(0).setTextFormat(bNFormat);

         }
      
      private function boxOnMouseOut(evt:MouseEvent){
         thumbHider.alpha = .4;
         evt.target.parent.graphics.clear();
         evt.target.parent.graphics.lineStyle(1, 0xffffff, 1, true);
         evt.target.parent.graphics.drawRect(-1, -1, 112, 152);
         var bNFormat:TextFormat = new TextFormat("Trebuchet MS", 11, 0xffffff, false, null, null, null, null, TextFormatAlign.CENTER);
         evt.target.parent.getChildAt(0).getChildAt(0).setTextFormat(bNFormat);
         }
      
      private function boxOnPress(evt:MouseEvent){
                                  //nothing yet
                 }
      
      private function randomNumber(low:Number=NaN, high:Number=NaN):Number{
         var low:Number = low;
         var high:Number = high;
         
         if(isNaN(low))
         {
            throw new Error("low must be defined");
         }
         if(isNaN(high))
         {
            throw new Error("high must be defined");
         }
         return Math.round(Math.random() * (high - low)) + low;
      }
    }
}

Static Type Class Problem: Help With Script 3 Button
I'm trying to make my button work for a basic webpage. Every time I "test movie" it ignores the stop message and just loops through continuously. I get this message: 1061: Call to a possibly undefined method addEventListener through a reference with static type Class.

here is my code:Code:

stop();
import flash.events.MouseEvent;
bbsf_btn.addEventListener(MouseEvent.CLICK,bbsfclick);
function bbsfclick(event:MouseEvent):void {
   gotoAndStop("bbsfportfolio");
}

this seems like a simple problem, I just can't figure out what it could be. Thanks!

User Defined Base Class Linked With 2 Symbols Gives Error #1034: Type Coercion Failed
Hi, I have two movie clips in the library linked to the same base class, Container, with different class names defined in Properties. These clips each contain (nest) several other clips that are also linked to another base class, Contained. Is there something else that needs to be done to deal with nested clips like this? I'm not certain that nesting is an issue, but in a scenario with different symbols I could not replicate the problem. I've attached a simplified version of the problem .fla with the 2 .as files. I'm using the latest version of CS3. The error is: TypeError: Error #1034: Type Coercion failed: cannot convert Contained_AnteriorLeft@1c4ba431 to Contained_PosteriorLeft.

Tween Class, Does It Use Setinterval? Getting Strange Setinterval Type Problem
I have a gallery with small thumbnails. Upon clicking a thumbnail, I am using the Tween class to pull clips from an array and fade them between each other, loading the clips into a container.

When I click the thumbnail it loads the .swf fine and plays the Tween Class animation just as it's supposed to, however if I click any other thumbnail and go back to that first one the timing gets totally screwed up and the fades get jittery and overlap each other, much like it does with setInterval if you don't clear the intervals.

Is there a way to clear the Tween Class? Does it's timer run on setInterval?


This is the code I am using for the tween class


Thanks!


Code:
import mx.transitions.Tween;
import mx.transitions.easing.*;

//content movieclips put into an array
var mcArray:Array = new Array(content1, content2);
for (var k in mcArray) {
mcArray[k]._alpha = 0;
}

// tween class has something called "OnEnterFrameBeacon" and it is added to the stage
// when we import the as file, so I wanted to get rid of it.
var n:Number = 0;

function playFades() {
if (n<mcArray.length) {
var tween_handler1:Object = new Tween(mcArray[n], "_alpha", Strong.easeIn, 0, 100, 1, true);
tween_handler1.onMotionFinished = function() {
//trace("motion finished by "+mcArray[n]);
//n++;
var tween_handler2:Object = new Tween(mcArray[n], "_alpha", Strong.easeIn, 100, 0, 3.5, true);
tween_handler2.onMotionFinished = function() {
//trace("motion finished by "+mcArray[n]);
n++;
playFades();
};
};
} else {
n = 0;
playFades();
}
}
playFades();

Basic: How Can I Check For "a Type Of Class".
hi there people!

I am after some help with regards to a problem.

class AbstractModule

class FirstModule extends AbstractModule
class SecondModule extends AbstractModule
class ThirdModule extends AbstractModule

If i have these classes and in my main class i have:

var module:AbstractModule = new FirstModule();

Then how can i later base a conditional on if (module == FirstModule). I know this must be pretty basic but i am lost for the terms to search for.

Thanks

AS3: Casting
What is the difference between the following two statements?


ActionScript Code:
oBj1 = XML(oBj2);

and


ActionScript Code:
oBj1 = oBj2 as XML;

TIA, Eugene

Casting
Hi. Why does the attached lines return true, all three of them?

I understand the first returning true, I could even understand the second (strictly from the documentation it's ok to return true, but I think the "as" word is misleading), but I definitely don't understand why the third one is true.

Could some one explain me the exact semantics of those thing?

Thanks,
FaQ







Attach Code

var a:Sprite = new Sprite();

trace(a is Sprite, " = a is Sprite");
trace((a as DisplayObject) is Sprite, " = (a as DisplayObject) is Sprite");
trace(DisplayObject(a) is Sprite, " = DisplayObject(a) is Sprite");

Web Casting And Forums?
Hi folks, I need a pointer in the right direction here!
I have to setup a live webcam and a stills webcam on 10min refresh, aslo I need to make a forum page all in flash mx2004, can anyone point me in the direction of some good tutorials that I can just dive into?

Any help greatly appriciated.

Cheers.

Casting To Integer - What's Going On?
Look at this piece of code:

---------------------
alint = "0060";
trace (int(alint));
---------------------

this gives the value 48.

-48!?!? Where does that come from?

Help appreciated!

Casting An Array To An Int
I have this trace statement that reads out a array of an sql database-
trace(re.result._items[row][name]);

It prints this

2
8 *
3
1
5 *
2
0
5 *
1

I am trying to pull out the numbers with a * and make them seperate int's. Whats the best way to do this? Thanks in advance!

Casting To Integer?
Hi,

I am new to actionscript .
How do I cut off the decimal part of a Number to get only an integer.

I want to display % complete of an upload, and I want for example
75.43% to read 75%

So there is no integer type in ActionScript 2? only Number?
Is there some way to cast the darn thing ?
Or how do i do it?

-thanks

Instanceof And Casting; Anyone?
I'm setting up a nice event-handling class for taking care of the WebServiceConnector. I'm trying to do a clean cast of the result object, so I can get it back into type safety before handing it off to whatever class asked for it.

This (and variations thereof) is what I've been trying for a while now:


Code:
private function resultListener(res:Object)
{
if(res.target.results instanceof Boolean)
{
var return:Boolean = Boolean(res.target.results);
}
else if(res.target.results instanceof String)
{
var return:String = String(res.target.results);
}
else if(res.target.results instanceof Number)
{
var return:Number = Number(res.target.results);
}
else if(res.target.results instanceof Array)
{
var return:Array = Array(res.target.results);
}
else if(res.target.results instanceof Object) //(should) always true
{
var return:Object = Object(res.target.results);
}
}
None of these if-clauses are ever true. I would suspect - at the very least - that "instanceof Object" would be a catch-all, but it isn't. So... what type is results?

Do you have any idea as to how I can create this function - casting the result to a known AS-type?

Casting To Boolean From XML
How would you get Flash to recognise a value passed via XML as a boolean true/false...

Ive tried casting it to force it to be Boolean, which I think ive done correctly as:


ActionScript Code:
var run:Boolean = Boolean(xmlData.run.text())

Ive also tried removing the .text() however it always goes true, anyone know what i'm doing wrong...?

XML Node And Casting To Int
Just came across a strange behaviour in my Flex app when casting a xml node value to int.


Code:

//The attibute is set to '2'

var selectedCodeId:int = int(selectedFilterTreeNode.@codeId); //gave 2

var selectedCodeId:int = selectedFilterTreeNode.@codeId as int; //gave 0
Anyone seen this before?

SharedObject Casting
I'm storing a custom class object in a local SharedObject file, and then later trying to retrieve it. When I try to retrieve it, I get the following error:"Type Coercion failed: cannot convert Object@10547d59 to AS3.accounting.UserAccount."
The "@10547d59" changes every time obviously since it is just a temporary type name.

The 'basic' code to save the object is this:

ActionScript Code:
public function createUser(name:String, password:String):Boolean{
        var users:Object = userAccounts.data.users;
        if(!users) users = new Object();
        if(users[name]) return false;

        user = new UserAccount(name, password);
        users[name] = user;
        userAccounts.setProperty("users", users);
        userAccounts.flush();
        return true;
    }

The 'basic' code to load the object is this:

ActionScript Code:
public function findUser(name:String, password:String):Boolean{
        var users = userAccounts.data.users;
        if(!users || !users[name]) return false;
        user = users[name];
       
        return true;
    }

The object being sent-to the file is of type UserAccount, and the data retrieved is attempting to be placed in a UserAccount object, but the retrieved data doesn't seem to remember what type it was, and since Object is higher in the inheritance hierarchy it won't naturally convert it for me.

If you have any ideas, please feel free to share them. Otherwise, when I figure out the best solution I'll post it below.

Casting Types
How to I cast a String to an int in flash AS3

FLVMovie Casting
Hi there...

I'm new to the hole AS3 stuff... so sorry if the question is kind of silly.

For the Question:
I created my own FLVMovie Class:

Code:
package {

import flash.events.MouseEvent;
import fl.video.FLVPlayback;

public class FLVMovie extends FLVPlayback{

public function FLVMovie(){
this.addEventListener(MouseEvent.CLICK,clickHandler);
}

public function clickHandler(btn){
trace('movie click');
this.stop();
}
}
}
No for the question itself.... I have a existing FLVPlayback on the Stage... is there a way to convert / cast it into a FLVMovie so it has the Click event handler?

thx...

Casting MC To FLVPlayback
I need to create a FLVPlayback component dynamically, but it seems I can't cast the MovieClip returned by attachMovie to FLVPlayback class, it always return null. If I create a new document, it works well. I think this problem happen when I tell Flash to export classes at frame 2, but my component is being attached at frame 3. Is there a way to export classes for frame 2 and still being able to cast the Component?

Copyright © 2005-08 www.BigResource.com, All rights reserved