public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); switch (code) { case KeyEvent.VK_DOWN: sortDropActive(); break; case KeyEvent.VK_LEFT: moveleftActive(); break; case KeyEvent.VK_RIGHT: moveRightActive(); break; case KeyEvent.VK_UP: rotateRightActive(); break; case KeyEvent.VK_SPACE: hadnDropActive(); break; case KeyEvent.VK_P: //判断当前游戏状态 if (game_state == PLING) { game_state = STOP; } break; case KeyEvent.VK_C: if (game_state == STOP) { game_state = PLING; } break; case KeyEvent.VK_S: //重新开始 game_state = PLING; wall = new Cell[18][9]; currentOne = Tetromino.randomOne(); nextOne = Tetromino.randomOne(); totalScore = 0; totalLine = 0; break; } } }; //将窗口设置为焦点 this.addKeyListener(l); this.requestFocus();
时间: 2024-02-10 14:33:29 浏览: 119
java小游戏设计.doc
根据您提供的代码,我发现在这里的`this`可能是指的`JFrame`或`JPanel`等组件,这些组件需要获得焦点才能响应键盘事件。但是,在某些情况下,由于组件层次结构的问题,可能无法获得焦点,从而导致键盘事件无法响应。
解决此问题的一种方法是将焦点请求移动到组件的父级容器上,例如`JFrame`或`JPanel`等。请尝试将`this.requestFocus()`更改为`getParent().requestFocus()`或`getRootPane().requestFocus()`,看看问题是否得到解决。
阅读全文