[英]Button Class by instance name, Actionscript-3
我很習慣時間軸代碼,這讓我感到困惑。 如何獲取按鈕類以識別舞台上的按鈕實例?
請幫忙。
......剛剛修改過
Buttons.fla
Class: 'Buttons'
Button with instance name placed on stage
Buttons.as
package {
import flash.display.MovieClip;
public class Buttons extends MovieClip {
public function Buttons() {
mc.addEventListener(MouseEvent.MOUSE_DOWN, onClick);
stage.addChild(this);
}
public function onClick(event:MouseEvent):void{
trace("Hello World");
}
}
}
錯誤:
1120:未定義的屬性
錯誤表明它是鼠標事件,而不是我的實例名稱mc。
您缺少大括號和mc的定義以及MouseEvent的導入(上面問題的根源):
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Buttons extends MovieClip {
public function Buttons() {
//it's better to use "this" here instead of adding another
//instance of movieclip named "mc"
this.addEventListener(MouseEvent.MOUSE_DOWN, onClick);
}
public function onClick(event:MouseEvent):void{
trace("Hello World");
}
}
}
當然,還有其他幾種/更好的方法可以實現這些相同的結果,但至少應該解決您的編譯問題。 現在,要將其添加到舞台上,您需要將其添加到存在的內容中。 一種簡單的方法是將以下行放在this.addEventListener下面:
stage.addChild(this);
如果您對此工作有其他疑問,請告訴我。 我希望指出你正確的方向,
--gMale
編輯:
響應下面的評論,這里是Flash文件的鏈接 。 我試圖遵循你正在做的事情的意圖。 在IDE中編寫了一個快速可點擊按鈕,在一個單獨的* .AS文件中編碼了一個快速可點擊按鈕:
這可能有助於'mc'實例
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Buttons extends MovieClip {
public function Buttons() {
//it's better to use "this" here instead of adding another
//instance of movieclip named "mc"
this.addEventListener(MouseEvent.MOUSE_DOWN, onClick);
}
public function onClick(event:MouseEvent):void{
trace("Hello World");
//PASS IT INTO THE BRACKETS
stage.addChild(mc);//<--------------------------
}
}
}
要訪問在IDE中創建的實例,您需要使用[]語法調用它們,這有效:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Buttons extends MovieClip {
public function Buttons() {
this["mc"].addEventListener(MouseEvent.MOUSE_DOWN, onClick);
//stage.addChild(this); // this is really not useful
}
public function onClick(event:MouseEvent):void{
trace("Hello World");
}
}
}
另請注意,您需要導入MouseEvent。 :)
如果你真的需要能夠通過mc訪問你的按鈕,它需要更多的代碼:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class Buttons extends MovieClip {
protected var mc:MovieClip;
public function Buttons() {
if(this["mc"] is MovieClip){
mc = this["mc"];
}else{
//you probably want to create it if not found on the stage.
}
mc.addEventListener(MouseEvent.MOUSE_DOWN, onClick);
}
public function onClick(event:MouseEvent):void{
trace("Hello World");
}
}
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.