KeyListener in Java is abstract; cannot be instantiated?

Tomek picture Tomek · Nov 13, 2008 · Viewed 13.2k times · Source

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

Answer

Jon Skeet picture Jon Skeet · Nov 13, 2008

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.