我是编程新手,如果我犯了愚蠢的错误,请原谅我。
我想制作一个游戏,我开始制造玩家,这就是我被困在的地方。我正在尝试使用Keybindings(JComponent的InputMap和ActionMap)来让玩家移动,但是真的很奇怪。当我拿着“A”让玩家向左移动时,这就是他所做的。但如果我按“D”让他向右移动,他就会停滞不前。然后,如果我释放并再次按“D”,它确实会移动。我的所有键盘都会出现这种情况,使用KeyListener时遇到了类似的问题。
这似乎是另一个类的问题,比如Player类,但它不是:当我描述的情况发生时,我创建的AbstractActions没有被调用!当我使用KeyListener时,这与KeyPressed()方法相同。
这是我管理键盘输入的课程:
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
public class KeyManager {
private JLabel keyManager;
private Action leftTrue, leftFalse, rightTrue, rightFalse;
public boolean left = false, right = false, up = false, down = false;
public KeyManager() {
initActions();
keyManager = new JLabel();
System.out.println("called");
keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("D"), "pressed_D");
keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released D"), "released_D");
keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("A"), "pressed_A");
keyManager.getInputMap(JLabel.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("released A"), "released_A");
keyManager.getActionMap().put("pressed_D", rightTrue);
keyManager.getActionMap().put("pressed_A", leftTrue);
keyManager.getActionMap().put("released_D", rightFalse);
keyManager.getActionMap().put("released_A", leftFalse);
}
public JLabel getKeyManager() {
return keyManager;
}
private void initActions() {
leftTrue = new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("pressed a");
left = true;
}
};
leftFalse = new AbstractAction() {
private static final long serialVersionUID = 2L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("released a");
left = false;
}
};
rightTrue = new AbstractAction() {
private static final long serialVersionUID = 3L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("pressed d");
right = true;
}
};
rightFalse = new AbstractAction() {
private static final long serialVersionUID = 4L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("released d");
right = false;
}
};
}
}
JLabel对象被添加到另一个类
中的JFrame中我觉得我对这个问题的解释没有多大意义,所以这里有一个关于正在发生的事情的视频: