这是我的代码。
基本上,我创建了一个操纵动画的player
对象;但GameController
通过公共静态方法发送Player
命令。
但是,由于我的keyPressed
,keyReleased
和keyTyped
无效,因此我遇到了问题。
我输入了打印语句来检查KeyEvent
是否会显示任何内容但是没有显示。我还用mouseListener
检查了我的代码。因此,我不确定我做错了什么。
import objectdraw.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class GameController extends WindowController implements KeyListener, MouseListener {
Player player;
public GameController() {
super();
}
public void begin() {
Image sprite0 = getImage("1.png");
canvas.addKeyListener(this);
canvas.addMouseListener(this);
player = new Player (250, 0, sprite0 ,canvas);
}
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
}
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyChar());
}
public void keyTyped(KeyEvent e) {
}
public void mouseEntered( MouseEvent e ) { }
public void mouseExited( MouseEvent e ) { }
public void mousePressed( MouseEvent e ) {
if (Player.canJump && !Player.falling) {
Player.canJump = false;
Player.falling = false;
Player.jumping = true;
}
}
public void mouseReleased( MouseEvent e ) { }
public void mouseClicked( MouseEvent e ) {
}
}
答案 0 :(得分:2)
答案 1 :(得分:2)
您的组件似乎无法集中精力。使用KeyListener
必须具有重点,必须成为焦点。
相反,您可以使用KeyBindings绑定特定操作的密钥。
简单示例:
AbstractAction escapeAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
//code here example
((JComponent)e.getSource()).setVisible(Boolean.FALSE);
}};
String key = "ESCAPE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
component.getActionMap().put(key, escapeAction);
您可以使用这些JComponent常量
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT WHEN_FOCUSED WHEN_IN_FOCUSED_WINDOW
另外检查Single Responsability Principle似乎你的gameController太多了,MouseListener
KeyListener
还有WindowController
。而不是考虑如果不是更好,你的班级中有私人班级,例如
public class GameController extends WindowController{
private class MyMouselistener implements MouseListener{
//code here
}
}