keylistener作为对象的子类不起作用

vjhs03f7  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(459)

基本上我想做的是,我有一个对象,叫做mainball。mainball有一个keydecater类作为其内部类,keydecater被添加到构造函数的mainball中。mainball是在游戏中创建的,但是mainball不响应击键。

  1. public Mainball(){
  2. super(150,150,SIZE,SIZE);
  3. c= Color.RED;
  4. addKeyListener(new KeyDetecter());
  5. }
  6. class KeyDetecter extends KeyAdapter{
  7. public KeyDetecter(){
  8. }
  9. double velocityfactor = 0.8;
  10. public void keyPressed(KeyEvent e){
  11. if(e.getKeyChar() == 'a'){
  12. x_velocity = -velocityfactor;
  13. }
  14. if(e.getKeyChar() == 'd'){
  15. x_velocity = velocityfactor;
  16. }
  17. if(e.getKeyChar() == 's'){
  18. ball.y_velocity = velocityfactor;
  19. }
  20. if(e.getKeyChar() == 'w'){
  21. y_velocity = -velocityfactor;
  22. }
  23. if(e.getKeyCode() == '1'){
  24. Shoot_Type = the_Game.SHOOT_ARROW;
  25. }
  26. if(e.getKeyCode() == '2'){
  27. Shoot_Type = the_Game.SHOOT_PARTICLE;
  28. }
  29. }

游戏也要求关注这里的窗口

  1. if(button.getText().equals("Game")){
  2. try {
  3. game.walls = (ArrayList<wall>) SaveNLoad.load("wall_info.txt");
  4. } catch (Exception e1) {
  5. game.walls = new ArrayList<wall>();
  6. }
  7. frame.remove(current_panel);
  8. frame.add(game);
  9. game.ball.requestFocusInWindow(); /* ball is an mainball instance */
  10. current_panel = game;
  11. game.ball.x_center = 100;
  12. game.ball.y_center = 40;
  13. game.ball.y_velocity = 0;
  14. }
bfrts1fy

bfrts1fy1#

KeyEvent 这个 getKeyChar() 方法状态:
按键按下和按键释放事件不用于报告字符输入。因此,此方法返回的值保证仅对键类型的事件有意义。
因此,在上面的例子中,我认为如果将密钥处理的整个代码放在 KeyAdapter's keyTyped(KeyEvent e) 方法。

c2e8gylq

c2e8gylq2#

好吧,我给你做了测试,效果很好。

  1. public static void main(String[] args) {
  2. JFrame t = new JFrame();
  3. t.setSize(500, 500);
  4. t.addKeyListener(new KL());
  5. t.setVisible(true);
  6. }
  7. public static class KL extends KeyAdapter{
  8. public void keyPressed(KeyEvent e){
  9. if(e.getKeyChar() == 'a') System.out.println("a pressed");
  10. }
  11. }

相关问题