"null object reference" ActionScript 3 中的错误



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

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>

您得到#1009错误,因为您的resize事件是在创建对象之前激发的。所以,你应该等待,然后你的应用程序被添加到stage中,以便能够使用stage对象。

为此,我认为最好的事件是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);
}

希望这能有所帮助。

最新更新