如何在flex中为自定义组件编写事件?

时间:2010-01-04 13:19:58

标签: flex events custom-component

我编写了一个用于在Flex中绘制圆形的自定义组件。但是当我尝试为该组件编写click事件或mouseDown事件时,它不起作用。

我在VBox中有圆形组件。

 <mx:VBox label="Currents Quote" width="100%" backgroundColor="#DDDDDD">

<comp:MyCircle id="circlle" x1="175" y1="150" 
                    radius="140" click='{Alert.show("Hello");}'
                    mouseDown="handleMouseDown(event);"/>
<comp:MyLine x1="175" y1="104"/> 
 </mx:VBox>

  private function handleMouseDown(event:MouseEvent):void {

        var pt:Point = new Point(event.localX, event.localY);
        pt = event.target.localToGlobal(pt);   
        pt = circlle.globalToContent(pt);   
        var whichColor:String = "border area";

        if (pt.x < 150) {
            if (pt.y < 150)
                whichColor = "red";
            else
                whichColor = "blue";
        }
        else {
            if (pt.y < 150)
                whichColor = "green";
            else
                whichColor = "magenta";
        }

        Alert.show("You clicked on the " + whichColor);
      }

圆形组件:

  package components
  {
 import mx.core.UIComponent;

 public class MyCircle extends UIComponent
 {
       public var x1:int; 
          public var y1:int; 
          public var radius:int; 

          override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void 
         { 
        graphics.lineStyle(1, 0x000000);
        graphics.drawCircle(x1, y1, radius); 

        graphics.lineStyle(1, 0x000000);
        graphics.drawCircle(x1, y1, radius-40); 

        graphics.lineStyle(1, 0x000000);
        graphics.drawCircle(x1, y1, radius-100);
         }
     }
 }

“Hello”警报仅显示在特定点,并且在该点处猜测(175,150)圆的x,y坐标。但是,无论何时单击MyCircle组件,都不应该显示它?如何以这种方式启用它?

此外,mouseDown函数对MyCircle不起作用,但如果有VBox事件,则会显示警报。为什么这样?有人可以指导我吗?

我应该以不同的方式为自定义组件编写事件吗?

2 个答案:

答案 0 :(得分:1)

我不确定这是否适用,但是有一个错误,一些UIComponent没有正确识别click / mouseDown事件,除非它们有背景颜色。看看在圆圈中添加背景颜色是否有帮助。

答案 1 :(得分:0)

您的代码中也存在一些错误,例如,您的动作脚本周围缺少脚本标记,您可能需要导入警报。

 <mx:VBox label="Currents Quote" width="100%" backgroundColor="#DDDDDD">

<comp:MyCircle id="circlle" x1="175" y1="150" 
                    radius="140" click='{Alert.show("Hello");}'
                    mouseDown="handleMouseDown(event);"/>
<comp:MyLine x1="175" y1="104"/> 
 </mx:VBox>

<mx:Script>
<![CDATA[
  private function handleMouseDown(event:MouseEvent):void {

        var pt:Point = new Point(event.localX, event.localY);
        pt = event.target.localToGlobal(pt);   
        pt = circlle.globalToContent(pt);   
        var whichColor:String = "border area";

        if (pt.x < 150) {
            if (pt.y < 150)
                whichColor = "red";
            else
                whichColor = "blue";
        }
        else {
            if (pt.y < 150)
                whichColor = "green";
            else
                whichColor = "magenta";
        }

        Alert.show("You clicked on the " + whichColor);
      }
]]>
</mx:Script>