views:

3294

answers:

3

Hey all,

I am trying to create a Key Listener in java however when I try

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?

Thanks,

Tomek

+6  A: 

KeyListener is an interface - it has to be implemented by something. So you could do:

KeyListener listener = new SomeKeyListenerImplementation();

but you can't instantiate it directly. You could use 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.

Jon Skeet
+1  A: 

KeyListener is an interface, that means you can write a class based on it and implement its functions. Perhaps this tutorial helps.

schnaader
KeyListener is an interface, see http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/KeyListener.html
dhiller
Sorry for that, I'm not that familiar with Java and its terminology, thanks for clarification.
schnaader
+4  A: 

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 listener = new KeyAdapter()
{
    public void keyPressed(KeyEvent e) { /* ... */ }
};

This could save you a bit of work.

Joey Gibson