Почему я не могу получить возвращаемое значение из своего пользовательского класса? - PullRequest
0 голосов
/ 22 июля 2010
package com.adam.etutorial

{import flash.display.MovieClip;import flash.text.TextField;импорт flash.display.Sprite;import flash.text.TextFormat;import flash.display.Shape;

public class adamsboxmaker
{

    //(boxWidth, boxHeight, lineColour, lineThickness, beginFillColour, fillIf, fontcolour, fontsize, fonttype, textFormat, textWidth, textHeight, text, Xoffset, Yoffset, textIf)
    public function adamsboxmaker(boxWidth:Number,boxHeight:Number,lineColour:Number,lineThickness:int, beginFillColour:Number, fillIf:Boolean, fontColour:Number, fontSize:int, fontType:String, textWidth:Number, textHeight:Number, txt:String, Xoffset:Number, Yoffset:Number, textIf:Boolean)
    {

        createBox(boxWidth,boxHeight,lineColour,lineThickness, beginFillColour, fillIf, fontColour, fontSize, fontType, textWidth, textHeight, txt, Xoffset, Yoffset, textIf);


    }

    private function createBox(boxWidth:Number,boxHeight:Number,lineColour:Number,lineThickness:int, beginFillColour:Number, fillIf:Boolean, fontColour:Number, fontSize:int, fontType:String, textWidth:Number, textHeight:Number, txt:String, Xoffset:Number, Yoffset:Number, textIf:Boolean)
    {


        /*BUILD CONTAINER*/
        var container:MovieClip = new MovieClip();
        /*END CONTAINER*/

        /*BUILD BOX*/
        var theBox:Shape = new Shape();
        container.addChild(theBox);
        theBox.graphics.lineStyle(lineThickness, lineColour);

        if (fillIf == true)
        {
            theBox.graphics.beginFill(beginFillColour);
        }

        theBox.graphics.moveTo(0, 0);
        theBox.graphics.lineTo(boxWidth, 0);
        theBox.graphics.lineTo(boxWidth, boxHeight);
        theBox.graphics.lineTo(0, boxHeight);
        theBox.graphics.lineTo(0, 0);

        if (fillIf == true)
        {
            theBox.graphics.endFill();
        }
        /*END BOX*/

        if (textIf == true)
        {
            /*BUILD FORMATTING*/
            var myFormat:TextFormat = new TextFormat();
            myFormat.color = fontColour;
            myFormat.size = fontSize;
            myFormat.font = fontType;
            /*END FORMATTING*/

            /*BUILD TEXTFIELD*/
            var theText:TextField = new TextField();
            theText.text = txt;
            theText.x = Xoffset;
            theText.y = Yoffset;
            theText.width = textWidth;
            theText.height = textHeight;
            theText.wordWrap = true;
            theText.setTextFormat(myFormat);
            container.addChild(theText);
            /*END TEXTFIELD*/
        }
        container.visible = false;

    return container;

    }

}

}

Это мой первый треск при написании класса, и после прочтения это то, что у меня есть.

По сути,Я хочу иметь возможность написать var txt: adamsboxmaker = new adamsboxmaker (параметры);

и иметь txt быть экранным объектом из возвращенного мувиклипа.Но этого не происходит.Может ли кто-нибудь указать мне правильное направление?

Ответы [ 2 ]

3 голосов
/ 22 июля 2010

Хорошо. Так что проблема здесь в небольшом недоразумении. Вы создаете экземпляр класса adamsboxmaker, и затем ссылка автоматически возвращается и сохраняется в переменной txt. Так работают объектно-ориентированные языки.

То, что вы пытаетесь сделать, это использовать фабричный метод для создания объекта. Чтобы реализовать это, измените ваш createBox на общедоступную статическую функцию

 public static function createBox(boxWidth:Number,boxHeight:Number,lineColour:Number,lineThickness:int, beginFillColour:Number, fillIf:Boolean, fontColour:Number, fontSize:int, fontType:String, textWidth:Number, textHeight:Number, txt:String, Xoffset:Number, Yoffset:Number, textIf:Boolean){

и удалите вызов из конструктора.

public function adamsboxmaker(boxWidth:Number,boxHeight:Number,lineColour:Number,lineThickness:int, beginFillColour:Number, fillIf:Boolean, fontColour:Number, fontSize:int, fontType:String, textWidth:Number, textHeight:Number, txt:String, Xoffset:Number, Yoffset:Number, textIf:Boolean)
{

           //removed call

}

Тогда все, что вам нужно сделать, это

txt = adamsboxmaker.createBox(paramters);

Re: Вопрос в комментарии

В этом случае вы хотите, чтобы ваш adamsboxmaker был коробкой. Поэтому сначала сделайте расширение класса MovieClip

public class adamsboxmaker extends MovieClip
{

Теперь вы можете считать, что экземпляр этого класса совпадает с контейнером: MovieClip, который вы создавали. Добавьте этот код в конструктор:

      public function adamsboxmaker(boxWidth:Number,boxHeight:Number,lineColour:Number,lineThickness:int, beginFillColour:Number, fillIf:Boolean, fontColour:Number, fontSize:int, fontType:String, textWidth:Number, textHeight:Number, txt:String, Xoffset:Number, Yoffset:Number, textIf:Boolean){

                    var theBox:Shape = new Shape();
                    addChild(theBox); //we add it to this, rather than a container
                    theBox.graphics.lineStyle(lineThickness, lineColour);

                    if (fillIf == true)
                    {
                        theBox.graphics.beginFill(beginFillColour);
                    }

                    theBox.graphics.moveTo(0, 0);
                    theBox.graphics.lineTo(boxWidth, 0);
                    theBox.graphics.lineTo(boxWidth, boxHeight);
                    theBox.graphics.lineTo(0, boxHeight);
                    theBox.graphics.lineTo(0, 0);

                    if (fillIf == true)
                    {
                        theBox.graphics.endFill();
                    }
                    /*END BOX*/

                    if (textIf == true)
                    {
                        /*BUILD FORMATTING*/
                        var myFormat:TextFormat = new TextFormat();
                        myFormat.color = fontColour;
                        myFormat.size = fontSize;
                        myFormat.font = fontType;
                        /*END FORMATTING*/

                        /*BUILD TEXTFIELD*/
                        var theText:TextField = new TextField();
                        theText.text = txt;
                        theText.x = Xoffset;
                        theText.y = Yoffset;
                        theText.width = textWidth;
                        theText.height = textHeight;
                        theText.wordWrap = true;
                        theText.setTextFormat(myFormat);
                        container.addChild(theText);
                        /*END TEXTFIELD*/
                    }
                    visible = false;
     }

Теперь вы можете идти

txt = new adamsboxmaker(parameters);
addChild(txt);
0 голосов
/ 22 июля 2010

Просто пару мелочей, которые можно было бы добавить, которые могли быть пропущены.

В соответствии с передовой практикой все функции должны иметь возвращаемый тип EXCEPT для конструкторов классов, подобных всем, и все классы должны начинаться с верхнего регистра и иметь регистр заголовка.

public class AdamsBoxMaker 
{ 
  public function AdamsBoxMaker() 
  { 
    //your constructor 
  }

  public function anotherMethod( someParameter : String ) : String 
  { 
    //returns a String 
    return someParameter += " awesome!"; 
  } 

  private function anotherPrivateMethod( someParameter : String ) : void 
  { 
    //returns nothing 
  } 

НТН

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...