我對Flex和ActionScript很陌生,我試圖做一個應用程序,其目的只是爲了能夠在面板上動態創建矩形:在鼠標下創建矩形時創建並在鼠標移動事件上進行更新(左鍵按住),然後用鼠標向上實現矩形。事件問題(未檢測到)
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="550" height="400"
creationComplete="this.onCreationComplete(event);">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.graphics.SolidColor;
import spark.primitives.Graphic;
import spark.primitives.Rect;
public static const WIDTH:int = 480;
public static const HEIGHT:int = 300;
public static const BACKGROUND:int = 0xEFEFEF;
public static const CURRENT_FILL:SolidColor = new SolidColor(0x00AA00, 0.75);
protected var rectangles:ArrayCollection = null;
protected var currentRect:Rect = null;
protected var dragging:Boolean = false;
protected function onCreationComplete(event:FlexEvent):void
{
this.rectangles = new ArrayCollection();
this.sprite.graphics.beginFill(BACKGROUND);
this.sprite.graphics.drawRect(0, 0, this.sprite.width, this.sprite.height);
this.sprite.graphics.endFill();
this.sprite.addEventListener(MouseEvent.MOUSE_DOWN, this.onMouseDown);
this.sprite.addEventListener(MouseEvent.MOUSE_UP, this.onMouseUp);
}
protected function onMouseDown(event:MouseEvent):void
{
this.currentRect = new Rect();
this.currentRect.y = 10;
this.currentRect.height = this.sprite.height - (10 * 2);
this.currentRect.x = event.localX;
this.currentRect.width = 1;
this.panel.addElement(this.currentRect);
this.dragging = true;
this.sprite.addEventListener(MouseEvent.MOUSE_MOVE, this.onMouseMove);
}
protected function onMouseUp(event:MouseEvent):void
{
if (this.dragging)
{
this.sprite.removeEventListener(MouseEvent.MOUSE_MOVE, this.onMouseMove);
this.rectangles.addItem(this.currentRect);
this.dragging = false;
}
}
protected function onMouseMove(event:MouseEvent):void
{
if (this.dragging)
{
this.currentRect.width = event.localX - this.currentRect.x;
}
}
]]>
</fx:Script>
<s:Panel id="panel" x="10" y="10" title="Calendar">
<s:SpriteVisualElement id="sprite" width="{WIDTH}" height="{HEIGHT}" />
</s:Panel>
</s:WindowedApplication>
所有工作正常,但現在我想要做一些動作,當用戶點擊(或雙擊,或者你想要的)上的一個矩形。我試圖在每個矩形上添加一個事件(在onMouseUp中添加this.currentRect.addEventListener(MouseEvent.DOUBLE_CLICK,myMethod)),但相應的方法從未執行...
問題是什麼?
謝謝你的建議!實際上,我使用圖形API在後臺繪製一些圖形(我不需要與這些圖形進行交互),但正如您在'onMouseDown'方法中所見,我創建了Spark原始圖形並將其添加到面板使用'addElement'... – jroy
啊。我明白你現在在做什麼。嘗試添加偵聽器_before_將其添加爲元素,以便爲玩家提供一個「線索」,您希望爲每個Rect單獨顯示對象(Rects不能單獨接收鼠標事件)。如果這不起作用,請按照我的建議嘗試使用DataGroup,以便通過MXML完成所有工作。 –
好吧我只是不知道Rects無法接收鼠標事件。我試圖添加偵聽器,但它沒有奏效......我想我會嘗試你或tousdan的建議,謝謝。 – jroy