ActionScript 3中的“null对象引用”错误

时间:2016-05-10 14:52:44

标签: actionscript-3 flash flex flex4

我使用我的应用程序的resize处理程序来调整我的组件大小,但它抛出了这个错误:

TypeError: Error #1009: Cannot access a property or method of a null object reference

这是我的代码:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
           xmlns:s="library://ns.adobe.com/flex/spark" 
           xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
           resize="application2_resizeHandler(event)" >
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            import mx.events.ResizeEvent;

            private var employeeName:String = 'ravi';

            protected function application2_resizeHandler(event:ResizeEvent):void
            {
                mainGroup.width = stage.width - 10;
                mainGroup.x = 5;                    
            }

        ]]>
    </fx:Script>    
    <s:Group width="100%" height="100%">
        <s:VGroup id="mainGroup" >
            <s:Label id="employeeNameLabel" text="{employeeName}" />
            <s:Label id="departmentLabel"  />
        </s:VGroup>

        <s:Button id="getData" />
    </s:Group>
</s:Application>

1 个答案:

答案 0 :(得分:-1)

您收到了#1009错误,因为在创建对象之前触发了resize事件。因此,您应该等待,并且您的应用程序已添加到舞台中以便能够使用舞台对象。

为此,我认为最好的事件是applicationComplete事件,然后您可以添加resize事件来调整组件的大小......

所以你可以这样做,例如:

<s:Application 
    xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
    applicationComplete="application2_applicationCompleteHandler(event)" >

然后

protected function application2_applicationCompleteHandler(event:FlexEvent):void
{
    // if you want you can resize your component for the 1st time
    // by calling the application2_resizeHandler() function
    application2_resizeHandler(new ResizeEvent(ResizeEvent.RESIZE));

    // add the resize event listener to your app
    event.target.addEventListener(ResizeEvent.RESIZE, application2_resizeHandler);
}

希望可以提供帮助。