I'm trying to capture key events in a mx:Image and I can't get it to work.
<?xml version="1.0" encoding="utf-8" ?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" />
<mx:Canvas width="100%" height="100%">
<mx:Label id="lab" x="50" y="20" text="Nothing"/>
<mx:Image x="50" y="50" source="@Embed('image.png')" keyDown="lab.text='Something';"/>
</mx:Canvas>
</mx:Application>
When I press a key when the mouse is over the image I expect the label text to change to "Something", but nothing happens. I've done all sorts of combination of enabled and putting the keyDown on the canvas and the label as well.
What am 开发者_运维知识库I missing?
The issue is one of focus. Key down events are only generated within a component when that component (or one of its descendants) has focus. In order for an Image to receive focus, you must set focusEnabled to true. This, however, requires that the user tab to give the Image focus, since clicking on an Image does not convey focus, much less mousing over it.
If you want to listen for the key down event when the user's mouse is over the Image, you can manually assign focus to the Image when the user moves their mouse over it.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
import mx.managers.IFocusManagerComponent;
private var oldFocus:IFocusManagerComponent;
public function imageMouseOver(event:MouseEvent):void {
oldFocus = focusManager.getFocus();
var newFocus:UIComponent = event.target as UIComponent;
newFocus.setFocus();
}
private function imageMouseOut(event:MouseEvent):void {
if (oldFocus) {
oldFocus.setFocus();
}
}
]]>
</mx:Script>
<mx:Canvas width="100%" height="100%">
<mx:Label id="lab" x="50" y="20" text="Nothing"/>
<mx:Image x="50" y="50" source="@Embed('image.png')" mouseOver="imageMouseOver(event)" mouseOut="imageMouseOut(event)" keyDown="lab.text='Something';" focusEnabled="true"/>
</mx:Canvas>
</mx:Application>
Alternately, you can assign a key down listener to the stage when the user mouses over the Image, and remove it when the user mouses out.
Image derives from (a.k.a "is a") SWFLoader. You need to add listeners to the content of the loader, not the loader itself. See this question for details, Interact with SWF Loader
精彩评论