在何处以及如何实例化 inputmaps 和 actionmaps

Where and how to instantiate inputmaps and actionmaps

我正在制作一个 classic "move image around on the screen" 程序。我试图让键绑定工作,而不是 Keylistener,但到目前为止没有成功。

我的对象在链表中

public LinkedList<GameObject> object = new LinkedList<GameObject>();

并通过

添加到此列表
public void addObject(GameObject object){
    this.object.add(object);
}

我的KeyBindingclass如下

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) {
    }
}

}

My Player class,它扩展了 GameObject class 看起来(略微压缩)为:

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);
}
}

不过我不确定如何 "activate" 键绑定。它应该在主循环中吗?它应该在 player.tick 方法中被调用以更新播放器图像并随后绘制它吗?

另外,inputmap 和 actionmap 是如何关联到 player 对象的?我试过这样做,但没有用:

public void registerKeyBinding(KeyStroke keyStroke, String name, Action action) {
    for (int i = 0; i < handler.object.size(); i++){
        GameObject player = handler.object.get(i);
        //find player
        if (player.getID() == ID.Player){
            InputMap im = player.getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = player.getActionMap();

            im.put(keyStroke, name);
            am.put(name, action);
        }
    }
}

我认为应该如何将我的播放器转换为 JComponent,但我不确定这是如何完成的(因为 Eclipse 告诉我它与我的 GameObject class 不兼容)。谁能指导我正确的方向?如果我不小心遗漏了一些重要信息(我很确定我遗漏了),请告诉我

您不需要 "activate" 键绑定,一旦您填充 ActionMap 它就已经激活了。你需要做的是实现Action对象的actionPerfomed方法。 Action 对象本质上是一个动作 处理程序 。它在创建后不应该做任何事情,它应该只在实际执行操作后做事。