Sunday, July 25, 2010

Detect MouseEvent in FilledElement

I am creating components dynamically using a class that I'm extending from FilledElement. I need to capture mouse events on these components, but Filled Elements cannot detect mouse events. Thankfully, I found a comment in a post on CodeDependent!

http://graphics-geek.blogspot.com/2010/05/video-flex-4-path-to-enlightenment.html

Using that information, in ActionScript, I added a Group and then added my component to the group.

Now I can detect whether my component was clicked and I can even change the stroke! I borrowed the hit test code from Chet's Top Drawer. Thanks to Chet and Guillaume!


//MXML
<s:Panel id="panel" width="563" height="373" x="76">
<s:layout>
<s:TileLayout>
</s:TileLayout>
</s:layout>
<s:Panel>


//ActionScript in MXML
//This is a bit klugey, but it works.
var mySymbol:MyComponent = new MyComponent();
var group:Group = new Group();
var i:IVisualElement = panel.addElement(group as IVisualElement);
group.addElement(mySymbol);
mySymbol.addListeners();

//ActionScript in component
//in the addListeners function:
this.parent.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);

//in handleMouseDown
var selectPoint:Point = localToGlobal(new Point(event.localX, event.localY));
//parent is the Group that was added in the MXML code
if (this.parent.hitTestPoint(selectPoint.x, selectPoint.y))
{
this.stroke = new SolidColorStroke(0x000000,2);
}

5 comments:

Unknown said...

Does this still have the problem that the group is a rectangle around your component? So the mouse event happens whenever you are in the rectangle, not just the component?

If not, what fixes that...?

Tina in Boston said...

Hi Jessica,

Thanks for your note -- that is a good question. I will have to test it out within the next few days. I'll post another comment after I've had a look.

Tina in Boston said...

Hi Jessica,

It appears that the group is not a rectangle around my component. If I change the component to a triangle, then it appears the group is a triangle as well. I create a new group but I don't draw it. The component is drawn using Graphics.drawPath.

Hope this helps!

Unknown said...

That's great. I'll have to look at the code more carefully. When I do it for a component that's a circle, the group sure looked like a square around it. However, I drew the circle with Ellipse, not a path. I'll have to try the path and see if that makes a difference....

Tina in Boston said...

Let me know how it turns out!