Java 中的 KeyListener 是抽象的;不能实例化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/286605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
KeyListener in Java is abstract; cannot be instantiated?
提问by Tomek
I am trying to create a Key Listener in java however when I try
我正在尝试在 java 中创建一个 Key Listener 但是当我尝试时
KeyListener listener = new KeyListener();
Netbeans is telling me that KeyListener is abstract;cannot be instantiated. I know that I am missing some other piece of this key listener, but since this is my first time using a key listener i am unsure of what else i need. Why is it telling me this?
Netbeans 告诉我 KeyListener 是抽象的;无法实例化。我知道我错过了这个关键侦听器的其他部分,但由于这是我第一次使用关键侦听器,我不确定我还需要什么。为什么要告诉我这些?
Thanks,
谢谢,
Tomek
托梅克
回答by Jon Skeet
KeyListeneris an interface - it has to be implemented by something. So you could do:
KeyListener是一个接口 - 它必须由某种东西来实现。所以你可以这样做:
KeyListener listener = new SomeKeyListenerImplementation();
but you can't instantiate it directly. You coulduse an anonymous inner class:
但你不能直接实例化它。您可以使用匿名内部类:
KeyListener listener = new KeyListener()
{
public void keyPressed(KeyEvent e) { /* ... */ }
public void keyReleased(KeyEvent e) { /* ... */ }
public void keyTyped(KeyEvent e) { /* ... */ }
};
It depends on what you want to do, basically.
基本上,这取决于你想做什么。
回答by Joey Gibson
KeyListener is an interface, so you must write a class that implements it to use it. As Jon suggested, you could create an anonymous class that implements it inline, but there's a class called KeyAdapter that is an abstract class implementing KeyListener, with empty methods for each interface method. If you subclass KeyAdapter, then you only need to override those methods you care about, not every method. Thus, if you only cared about keyPressed, you could do this
KeyListener 是一个接口,因此您必须编写一个实现它的类才能使用它。正如 Jon 建议的那样,您可以创建一个匿名类来实现它内联,但是有一个名为 KeyAdapter 的类,它是一个实现 KeyListener 的抽象类,每个接口方法都有空方法。如果你继承 KeyAdapter,那么你只需要覆盖你关心的那些方法,而不是每个方法。因此,如果你只关心 keyPressed,你可以这样做
KeyListener listener = new KeyAdapter()
{
public void keyPressed(KeyEvent e) { /* ... */ }
};
This could save you a bit of work.
这可以为您节省一些工作。

