【问题标题】:Changing text field of button in for loop在for循环中更改按钮的文本字段
【发布时间】:2013-09-06 17:31:50
【问题描述】:

我正在制作一个关卡选择屏幕,我需要文本字段来显示每个关卡的不同关卡编号。我真的不明白我在这里做错了什么,但我会回顾一下我所做的并发布相关代码。

我有一个按钮类(链接),在符号内我有一个动态文本字段。我有两类相关性,LevelSelectScreenLevelSelectButtons(它们是什么,不言自明)。我认为如果我在LevelSelectButtons 类中更改文本会很容易,只需执行levelText.text = "Wanted Text",其中levelText 是我的按钮的给定实例名称(只是我顶部的一个文本字段按钮的图形)。不幸的是,这给出了一个非常常见和烦人的错误:TypeError: Error #1009: Cannot access a property or method of a null object reference。

在我的循环过程中,我尝试在 LevelSelectScreen 类中做几乎相同的事情,但我得到了同样的错误。非常感谢有关如何让这个 levelText 工作的帮助!这是相关的代码。

LevelSelectScreen

    public class LevelSelectButtons extends SimpleButton {

        public var levelNumber:int;
        public var levelSelectScreen:LevelSelectScreen;

        public function LevelSelectButtons(i) {

            x = 200;
            y = 100 + 50*i;
            addEventListener(MouseEvent.CLICK,LevelSelectClicked,false,0,true)
            levelNumber = i;
            levelText.text = "Level" + i;
        }

    }

LevelSelectScreen

public class LevelSelectScreen extends MovieClip {

    public var levelSelectButtons:LevelSelectButtons;
    public var mainMenuButton:MainMenuButton;

    public function LevelSelectScreen() {

            for (var i:int = 1; i<=2; i++) 
            {
                levelSelectButtons = new LevelSelectButtons(i);
                addChild(levelSelectButtons);
            }
    }

}

【问题讨论】:

    标签: string actionscript-3 button textfield


    【解决方案1】:

    SimpleButton 中不能有动态文本字段。
    烦人,我知道。

    简单的解决方法是让 LevelSelectButton 包装一个 SimpleButton 而不是扩展它。然后,您的文本字段将位于无文本 SimpleButton 顶部的 LevelSelectButton 内。 (请务必在文本字段中将 mouseEnabled 设置为 false,这样它就不会干扰 SimpleButton 上的鼠标事件。

    更复杂的选择是编写您自己的自定义按钮类。
    这实际上并没有那么困难,但对于您在这里尝试做的事情可能有点过头了。

    【讨论】:

    • 为了补充这个答案,SimpleButton 是一个 DisplayObject 但不是 DisplayObjectContainer,因此不能包含其他 DisplayObject 对象(如 TextField)。我相信文本字段被“绘制”到 SimpleButton 中,而不是作为孩子添加到其中。 help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/…
    【解决方案2】:

    它是因为你没有声明 levelText 变量并且你试图访问它,因此无法访问 属性null 对象引用的方法。

    【讨论】:

    • 没有投反对票,但答案应该有助于找到解决方案,而不是简单地说明问题所在。我的意思是,我确实理解错误消息......这几乎是你的全部答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多