Karlovsky120
Karlovsky120

Reputation: 6362

KeyListener class

So, I'd like to create a keylistener inside my program that is applyable to all the classes in it (as when creating class as an object).

I don't know how to do it with a key(or any other) listener.

Usually it would go: class blabla extends JPanel {blablabla;}, but it doesn't work that way.

What is the way to go?

Upvotes: 1

Views: 2557

Answers (2)

Branislav Lazic
Branislav Lazic

Reputation: 14816

Consider creating a EventHandler class that implements KeyListener interface. Instatiate this class and pass to addKeyListener() method:

class EventHandler implements KeyListener{
    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }
}   

/**
* Usage
*/
EventHandler eh = new EventHandler();
nameOfComponent.addKeyListener(eh);  

Upvotes: 3

hamon
hamon

Reputation: 1016

KeyListener is an interface, so you should use the keyword implements instead of extends.

Upvotes: 0

Related Questions