我目前有这个游戏对象,我想知道为什么密钥控制不起作用。我认为它是因为我在JPanel上的某个地方有一个JTextBox,我删除它就是放弃焦点。虽然不完全确定。
我曾经让Game类控制这个动作,但是这个曾经工作过一次而且再也没有用了。再次,不知道为什么。
game.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
object.setVx(-10);
System.out.println("hello");
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
object.setVx(10);
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
object.setVy(10);
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
object.setVy(-10);
}
}
public void keyReleased(KeyEvent e) {
object.setVx(0);
object.setVy(0);
}
});
这是我尝试实现键绑定器的尝试,这似乎也不起作用:
public class Main implements Runnable{
public static Game game;
private static final String LEFT = "Left";
private Action left = new AbstractAction(LEFT) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(LEFT);
}
};
private static final String RIGHT = "Right";
private Action right = new AbstractAction(RIGHT) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(RIGHT);
}
};
public void run() {
/**here is where I try to put the keystroke in the map
*
*
*/
game.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), LEFT);
game.getActionMap().put(LEFT, left);
game.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), RIGHT);
game.getActionMap().put(RIGHT, right);
/**
*the mouselistener below works
*
*/
// add listeners for the game
game.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
object.jump();
}
});
// Start game
Game.reset();
这是我的可编辑和可运行的代码:它实现了相同的功能,并且它可以工作,我非常确定Game类或我的Main.java中还有其他东西正在破坏键绑定。
public class testKeyBinding implements Runnable {
private static final String LEFT = "Left";
private Action left = new AbstractAction(LEFT) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(LEFT);
}
};
private static final String RIGHT = "Right";
private Action right = new AbstractAction(RIGHT) {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(RIGHT);
}
};
@Override
public void run() {
JFrame frame = new JFrame();
frame.setSize(800, 800);
JPanel test = new JPanel();
test.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), LEFT);
test.getActionMap().put(LEFT, left);
test.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), RIGHT);
test.getActionMap().put(RIGHT, right);
frame.add(test);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new testKeyBinding());
}
}