我正在编写一个游戏,其中玩家使用WASD键移动。我知道有两种方法可以注册这种情况下的键盘输入:通过使用键侦听器或键适配器。
但是,还不清楚每个优点是什么,并且Java创建者没有理由拥有两个做相同事情的类。
我想知道哪种方法更好。
答案 0 :(得分:1)
公共抽象类KeyAdapter扩展对象实现KeyListener
用于接收键盘事件的抽象适配器类。此类中的方法为空。此类的存在是为了方便创建侦听器对象。
实际上,KeyAdapter 是一个实现KeyListener接口的类,因此我们不能谈论哪个更好,因为实现和接口不相等
您实际要做的只是扩展KeyAdapter类,并根据实际需要添加对键盘事件的一些其他支持
Here,您可以找到有关如何处理此主题的示例
答案 1 :(得分:0)
我想知道哪种方法更好。
这取决于您的应用程序设计。一些示例方案:
public class MyGuiApp extends KeyAdapter implements ActionListener {
// Override any -or- all of the three KeyAdapter class methods as needed
// No possibility of extending any other class
}
public class MyGuiApp implements KeyListener, ActionListener {
// Override all of the three methods of KeyListener
// Can have empty method bodies for the ones not used
// Possibility of extending any other class, later
}
public class MyGuiApp {
// ...
public void buildGui() {
// ...
JButton button = new JButton("Press me");
button.addKeyListener(new MyKeyListener());
// ...
}
// NOTE: Application will need only one of the implementations, in this sample.
// KeyAdapeter -or- KeyListener
private class MyKeyListener extends KeyAdapter {
// NOTE: Only one method is implemented - in this case
@Override public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
// do some ui related action...
}
}
}
private class MyKeyListener implements KeyListener {
// NOTE: Only all methods are reuired to be implemented - in this case
@Override public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
// do some ui related action...
}
}
@Override public void keyReleased(KeyEvent e) {
// No code - as its not used
}
@Override public void keyTyped(KeyEvent e) {
// No code - as its not used
}
}
}
示例代码链接:
KeyAdapter
:JButton KeyPressed - Nothing
Happens。KeyListener
:How to Write
a Key
Listener的Java教程的链接。答案 2 :(得分:0)
有一点小小的不同:
KeyListener
编译器会报错
error: <anonymous class$1> is not abstract and does not override abstract method
keyReleased(KeyEvent) in KeyListener
在IDE中你会得到
Add UnImplemented Methods
密钥适配器
您不会收到任何错误消息
因此,如果您只想KeyAdapter
某些方法,使用override
很方便。