Your class should have the addKeyListener
method. This is the case if your class is derived from Component or JComponent. So you should derive the class from either of these classes, like this:
class MyClass extends JComponent
Note that the inheritance does not have to be direct; if your class is derived from (for example) a JFrame, it indirectly inherits the addKeyListener
method, because JFrame is itself derived from Component.
Also, as is pointed out in the answers to this question, your class should be focusable for the Key Listener to work.
Update
You wrote in the comments that you were trying to use
this.addKeyListener( new CustomKeyListener( ) );
and got the error
Cannot use this in a static context
This happens because you called were making the call from a static method (the main
method in this case).
this
refers to the current instance of the class. In a static method, there is no instance - this is practically the definition of a static method.
What you should do, is create an instance:
MyClass newInstance = new MyClass( );
Now, you can add the key listener to that instance:
newInstance.addKeyListener( new CustomKeyListener( ) );
You could also do this in an instance method (any method that does not have the keyword static
), and call that method from your instance.
The official Java Tutorials have some more explanation on this subject.