使用KeyEvent时遇到问题

时间:2014-06-10 00:33:50

标签: java keyevent gridworld

我的问题是,如何使用move()KeyEvents来使KeyEvent.VK_DOWN方法工作? 我目前正在尝试使用import java.awt.event.KeyEvent;我将使用箭头键而不是小键盘来移动二维网格中的玩家。我的行为moveUp(); moveRight(); moveDown();moveLeft();位于我的超级班User和班级Player extends User中,并包含关键事件方法。当我使用箭头键时,actor根本不移动,但是当我手动点击网格中的actor并选择一个方法时它会移动。因此我的移动方法有效,所以我假设我的KeyEvent设置被破坏了。提供了显示我手动控制方法的图片。

包含移动方法的用户

package info.gridworld.actor;
import info.gridworld.grid.Grid;
import info.gridworld.grid.Location;

public class User extends Actor {
    private boolean isStopped = false;

    public User()
    {
        setColor(null);
    }

    public void moveUp(){
        moveTo(getLocation().getAdjacentLocation(Location.NORTH));
    }

    public void moveDown(){
        moveTo(getLocation().getAdjacentLocation(Location.SOUTH));
    }

    public void moveLeft(){
        moveTo(getLocation().getAdjacentLocation(Location.WEST));
    }

    public void moveRight(){
        moveTo(getLocation().getAdjacentLocation(Location.EAST));
    }
}  

Player类包含KeyEvents

package game.classes;
import info.gridworld.actor.User;
import java.awt.event.KeyEvent;


public class Player extends User{

    public Player(){
    }

    public void keyPressed(KeyEvent e){
        int keys = e.getKeyCode();
        if((keys == KeyEvent.VK_UP)){
            moveUp();
        }
        else if((keys == KeyEvent.VK_DOWN)){
            moveDown();
        }
        else if((keys == KeyEvent.VK_LEFT)){
            moveLeft();
        }
        else if((keys == KeyEvent.VK_RIGHT)){
            moveRight();
        }
    }


}  

主要课程

package game.classes;
import info.gridworld.grid.*;

public class PlayerRunner{


    private static GameGrid world = new GameGrid();

    public static void main(String[] args)
    {
        Player player = new Player();
        world.add(new Location(0, 0), player);
        world.show();
  }
}  

PreMove

moveDown() Selected

2 个答案:

答案 0 :(得分:1)

你正在扩展与GUI无关的Actor,而KeyEvents和相关的东西是摇摆不定的东西。您需要实际将KeyListener添加到JPanel。据我所知,现在你只需要在Actor类中使用额外的方法。

GUI实际上并不在AP测试中,所以它上面没有很多,但看起来你可以扩展info.gridworld.gui.GridPanel。因此将构造函数覆盖为:

public GridPanel(DisplayMap map, ResourceBundle res)
{
    super(map, res);
    addKeyListener(new KeyListener()
    {
        // Put the KeyListener methods here. 
        // (All of them: KeyListener is an interface
    }
}

这有点粗糙,但我认为它应该有效。

我假设你要引用一个你可以用箭头键移动的Actor,所以你可以调用它的移动方法。

答案 1 :(得分:0)

World类实际上有一个keyPressed()方法。您可以扩展World并覆盖此方法。它将为您提供一个字符串参数来代替KeyEvent。使用javax.swing.KeyStroke.getKeyStroke(description).getKeyCode()来确定按下了哪个键。世界级的来源是她:https://github.com/parkr/GridWorld/blob https://github.com/parkr/GridWorld/blob/master/framework/info/gridworld/world/World.java aster / framework / info / gridworld / world / World.java

至于访问Actor的方法,我会在World类中引用一个Actor。然后,当您添加要移动到世界的Actor时,您可以将其设置在那里。然后,当您处理击键时,您可以访问要操纵的Actor。