[英]Error using keyAdapter and keyEvent in java
I'm a beginner in programming and I have been working on a small project, the well known game called Tetris and I came upon this little problem and I would like you to help me with a solution. 我是编程的初学者,我一直在从事一个名为Tetris的知名小游戏,我遇到了这个小问题,希望您能为我提供解决方案。 I imported :
import java.awt.event.KeyAdapter
and import java.awt.event.KeyEvent
to be able to use my keyboard to play the game, but when I'm extending the class that I created to use the keys, it showing me an error!! 我导入了:
import java.awt.event.KeyAdapter
和import java.awt.event.KeyEvent
以便能够使用键盘玩游戏,但是当我扩展为使用键创建的类时,它显示我一个错误!
Here is the code: 这是代码:
addKeyListener(new TAdapter());
The error happens here saying this: 错误发生在这里这样说:
The method addKeyListener(keyListener) in the type Component is not applicable for the arguments(Board.TAdapter)
class TAdapter extends keyAdapter { // The second happens here: keyAdapter cannot be //resolved to a type public void keyPressed(keyEvent e) { // The third happens here: keyEvent //cannot be resolved to a type 类TAdapter扩展keyAdapter {//第二次发生在这里:keyAdapter无法//解析为类型public void keyPressed(keyEvent e){//第三次发生在这里:keyEvent //无法解析为类型
if (!isStarted || curPiece.getShape() == Tetrominoes.NoShape) {
return;
}
int keycode = e.getKeyCode();
if (keycode == 'p' || keycode == 'P') {
pause();
return;
}
if (isPaused)
{return;}
switch (keycode) {
case KeyEvent.VK_LEFT:
tryMove(curPiece, curX - 1, curY);
break;
case KeyEvent.VK_RIGHT:
tryMove(curPiece, curX + 1, curY);
break;
case KeyEvent.VK_DOWN:
tryMove(curPiece.rotateRight(), curX, curY);
break;
case KeyEvent.VK_UP:
tryMove(curPiece.rotateLeft(), curX, curY);
break;
case KeyEvent.VK_SPACE:
dropDown();
break;
case 'd':
oneLineDown();
break;
case 'D':
oneLineDown();
break;
}
}
You should avoid KeyListener
s, they have a number of issues related to focus, they can also bloat your code and make the management more difficult. 您应该避免
KeyListener
,它们有很多与焦点有关的问题,它们也可能使您的代码膨胀,并使管理更加困难。
You should instead, take advantage of the Key Bindings API , which provide a more reusable API and provide the means to determine the level of focus a component needs in order to recieve key events 相反,您应该利用Key Bindings API ,它提供了更可重用的API,并提供了确定组件接收关键事件所需的焦点级别的方法。
Use KeyAdapter
instead of keyAdapter
, and KeyEvent
instead of keyEvent
. 使用
KeyAdapter
代替keyAdapter
,并使用KeyEvent
代替keyEvent
。 The class names are case sensitive. 类名区分大小写。
class TAdapter extends KeyAdapter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.