基本上我想做的是,我有一个对象,叫做主球。主球有一个键侦测器类作为其内部类,键侦测器被添加到构造函数上的主球中。主球是在游戏中创建的,但主球不会响应按键。
public Mainball(){
super(150,150,SIZE,SIZE);
c= Color.RED;
addKeyListener(new KeyDetecter());
}
class KeyDetecter extends KeyAdapter{
public KeyDetecter(){
}
double velocityfactor = 0.8;
public void keyPressed(KeyEvent e){
if(e.getKeyChar() == 'a'){
x_velocity = -velocityfactor;
}
if(e.getKeyChar() == 'd'){
x_velocity = velocityfactor;
}
if(e.getKeyChar() == 's'){
ball.y_velocity = velocityfactor;
}
if(e.getKeyChar() == 'w'){
y_velocity = -velocityfactor;
}
if(e.getKeyCode() == '1'){
Shoot_Type = the_Game.SHOOT_ARROW;
}
if(e.getKeyCode() == '2'){
Shoot_Type = the_Game.SHOOT_PARTICLE;
}
}
游戏请求也集中在这里的窗口
if(button.getText().equals("Game")){
try {
game.walls = (ArrayList<wall>) SaveNLoad.load("wall_info.txt");
} catch (Exception e1) {
game.walls = new ArrayList<wall>();
}
frame.remove(current_panel);
frame.add(game);
game.ball.requestFocusInWindow(); /* ball is an mainball instance */
current_panel = game;
game.ball.x_center = 100;
game.ball.y_center = 40;
game.ball.y_velocity = 0;
}
从KeyEvent
的文档中,getKeyChar()
方法指出:
KEY_PRESSED和KEY_RELEASED事件不用于报告字符输入。因此,此方法返回的值保证仅对KEY_TYPED事件有意义。
因此,在上面的例子中,我认为如果您将用于键处理的整个代码放在KeyAdapter's keyTyped(KeyEvent e)
方法中会更好。
好的,我为您测试了它,这工作得很好。
public static void main(String[] args) {
JFrame t = new JFrame();
t.setSize(500, 500);
t.addKeyListener(new KL());
t.setVisible(true);
}
public static class KL extends KeyAdapter{
public void keyPressed(KeyEvent e){
if(e.getKeyChar() == 'a') System.out.println("a pressed");
}
}