Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyListener in Java is abstract; cannot be instantiated?

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

like image 845
Tomek Avatar asked Nov 13 '08 09:11

Tomek


People also ask

What is KeyListener in Java?

Interface KeyListenerThe listener interface for receiving keyboard events (keystrokes). The class that is interested in processing a keyboard event either implements this interface (and all the methods it contains) or extends the abstract KeyAdapter class (overriding only the methods of interest).

What is KeyListener and ActionListener in Java?

In our previous post, we learned how to use ActionListener and MouseListener. Today we will be discussing KeyListener. KeyListener in Java handles all events pertaining to any action with regards to keyboard. A method will be called whenever the user typed, pressed, or released a key in the keyboard.

What are the methods supported by KeyListener interface?

Methods of Java KeyListener The following are the commonly used methods: KeyPresses(KeyEventev): This method will be invoked when Key is pressed. KeyReleased(KeyEventev): This method will be invoked when a key is released. KeyTyped(KeyEventev): This method will be invoked when Key is typed.


2 Answers

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.

like image 110
Jon Skeet Avatar answered Sep 22 '22 00:09

Jon Skeet


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.

like image 21
Joey Gibson Avatar answered Sep 19 '22 00:09

Joey Gibson