我正在制作经典的"在屏幕上移动图像"程序。我试图让键绑定工作,而不是Keylistener,但到目前为止还没有成功。
我的对象位于链接列表中
//called when select an annotation
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
view.addGestureRecognizer(tapGestureRecognizer)
}
//Called when deselects the annotation
func mapView(mapView: MKMapView, didDeselectAnnotationView view: MKAnnotationView) {
view.removeGestureRecognizer(view.gestureRecognizers!.first!)
}
func tapped(sender: UITapGestureRecognizer) {
if let view = sender.view as? MKAnnotationView {
performSegueWithIdentifier("info", sender: view)
//do yours
}
}
并通过
添加到此列表中public LinkedList<GameObject> object = new LinkedList<GameObject>();
我的KeyBinding类如下
public void addObject(GameObject object){
this.object.add(object);
}
}
我的Player类扩展了GameObject类,看起来(略微浓缩)为:
public class KeyBindings extends JPanel{
private static final String accelerate = "accelerate";
public KeyBindings(){
System.out.println("test");
registerKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "UP-press", new ShuttleMove(accelerate));
}
public void registerKeyBinding(KeyStroke keyStroke, String name, Action action) {
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(keyStroke, name);
am.put(name, action);
}
class ShuttleMove extends AbstractAction {
public ShuttleMove(String movement) {
if (movement.equals("accelerate")){
//this.setVelocityForward(this.getVelocityForward() + 0.1);
System.out.println("accelerate");
}
}
public void actionPerformed(ActionEvent e) {
}
}
我不知道如何激活&#34;虽然键绑定。它应该在主循环中吗?它应该在player.tick方法中被调用以更新播放器图像并随后绘制它吗?
另外,inputmap和actionmap如何与播放器对象相关联?我尝试过做这样的事情,但是没有用:
public class Player extends GameObject {
Handler handler;
public Player(int x, int y, ID id, int width, int height, int rotation,double totalRotation, Handler handler, double velocityForward, double velocityRotate){
super(x, y, id, width, height, rotation, totalRotation);
this.handler = handler;
}
public void tick(){
x += this.getVelocityForward();
y += this.getVelocityForward();
}
public void render(Graphics2D g2d){
try {
player = ImageIO.read(new File("src/Game/images/shuttle3.png"));
} catch (IOException e) {
e.printStackTrace();
}
AffineTransform old = g2d.getTransform();
AffineTransform at = AffineTransform.getTranslateInstance(x,y);
g2d.drawImage(player, at,null);
g2d.setTransform(old);
}
}
我认为我的播放器应该如何转换为JComponent,但我不确定如何完成(因为Eclipse告诉我它与我的GameObject类不兼容)。谁能引导我朝着正确的方向前进?如果我意外地遗漏了一些重要信息(我很确定我这样做了),请告诉我。
答案 0 :(得分:0)
您无需“激活”键绑定,一旦填充ActionMap
,它就已经激活。你做需要做的是实现Action
对象的actionPerfomed方法。 Action
对象本质上是一个动作处理程序。它一旦创建就不应该做任何事情,它只应该在实际执行动作后做一些事情。