我正在研究一个java项目,并且我很难让键盘输入处理程序工作。我有两个单独的类,一个叫做KeyInput,一个叫做Player。当我启动Player类并按下一个键时,将不会打印任何内容,但如果我在KeyInput类中使用println,它将起作用。所以当你按下按钮时它会注册,只有当我想在Player类中使用它时它才会工作。
玩家类:
public class Player extends JFrame {
private static final int IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;
private BufferedImage img;
KeyInput input
public Player() {
super();
this.add(new JPanel() {
@Override
protected void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
});
img = new BufferedImage(660, 500, IMAGE_TYPE );
this.setSize(img.getWidth(), img.getHeight());
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
input = new KeyInput(this);
if(input.up.isPressed()){
System.out.println("Up");
}
this.setVisible( true );
}
}
KeyInput类:
public class KeyInput implements KeyListener {
BufferedImage img = null;
public KeyInput(Player player) {
player.requestFocus(); // click window to move bug fix he didn't add this
player.addKeyListener(this);
}
public class Key {
private int numTimesPressed = 0;
private boolean pressed = false;
public int getNumTimesPressed() {
return numTimesPressed;
}
public boolean isPressed() {
return pressed;
}
public void toggle(boolean isPressed) {
pressed = isPressed;
if (isPressed) {
numTimesPressed++;
}
}
}
public List<Key> keys = new ArrayList<Key>();
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public Key esc = new Key();
public void keyPressed(KeyEvent e) {
toggleKey(e.getKeyCode(), true);
}
public void keyReleased(KeyEvent e) {
toggleKey(e.getKeyCode(), false);
}
public void keyTyped(KeyEvent e) {
}
public void toggleKey(int KeyCode, boolean isPressed) {
if (KeyCode == KeyEvent.VK_W || KeyCode == KeyEvent.VK_UP
|| KeyCode == KeyEvent.VK_NUMPAD8) {
up.toggle(isPressed);
}
if (KeyCode == KeyEvent.VK_S || KeyCode == KeyEvent.VK_DOWN
|| KeyCode == KeyEvent.VK_NUMPAD2) {
down.toggle(isPressed);
}
if (KeyCode == KeyEvent.VK_A || KeyCode == KeyEvent.VK_LEFT
|| KeyCode == KeyEvent.VK_NUMPAD4) {
left.toggle(isPressed);
}
if (KeyCode == KeyEvent.VK_D || KeyCode == KeyEvent.VK_RIGHT
|| KeyCode == KeyEvent.VK_NUMPAD6) {
right.toggle(isPressed);
}
if(KeyCode == KeyEvent.VK_ESCAPE){
System.exit(0);
}
}
}
答案 0 :(得分:2)
您应该使用键绑定将键击指定给特定组件上的操作。
来自文档的qoute
component.getInputMap().put(KeyStroke.getKeyStroke("F2"),
"doSomething");
component.getActionMap().put("doSomething",
anAction);
//where anAction is a javax.swing.Action
https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html#howto