我有两节课。第一个(起始类):
package
{
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import tetris.*;
public class TetrisGame extends Sprite
{
private var _gameWell:Well;
public function TetrisGame()
{
_gameWell = new Well();
addChild(_gameWell);
}
}
}
第二个:
package tetris
{
import flash.display.Sprite;
import flash.events.KeyboardEvent;
public class Well extends Sprite
{
public function Well()
{
super();
addEventListener(KeyboardEvent.KEY_DOWN, onKeyboard);
}
private function onKeyboard(event:KeyboardEvent):void
{
//some code is here
}
}
}
但是当我按下键盘上的任何按钮时,子类Well
没有任何反应。有什么问题?
答案 0 :(得分:2)
好的,我懂了! =))
我应该专注于子精灵,以便它可以监听键盘事件。
package
{
import flash.display.Sprite;
import flash.events.KeyboardEvent;
import tetris.*;
public class TetrisGame extends Sprite
{
private var _gameWell:Well;
public function TetrisGame()
{
_gameWell = new Well();
addChild(_gameWell);
stage.focus = _gameWell;
}
}
}
答案 1 :(得分:1)
或作为替代;将事件监听器添加到阶段,因此它不依赖于Well具有焦点。
package tetris
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
public class Well extends Sprite
{
public function Well():void
{
super();
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboard);
}
private function onKeyboard(event:KeyboardEvent):void
{
//some code is here
}
}
}