简体   繁体   中英

Why am I not able to add a key listener?

I am trying to use a KeyListener in my program. I have added this class to my main class:

class CustomKeyListener implements KeyListener{
    @Override  
    public void keyTyped(KeyEvent k) {}
    @Override
    public void keyPressed(KeyEvent k) {}
    @Override
    public void keyReleased(KeyEvent k) {}    
}

However I am not able to add the addKeyListener(new CustomKeyListener()) method anywhere in my main class. What am I missing?

Based on my previous question I understand it will only work with a graphic interface.Should I just add some arbitrary form and it will work?

Can anyone shed some light on this problem?

Does your main class implement/extend a class that actually support the method iyou are trying to use?

Some context as to what your main-class is and what you want to achieve. Is it perhaps a scanner you need instead? If so then have a look over here to learn how to use it. http://www.tutorialspoint.com/java/util/java_util_scanner.htm

Also this might probably help as well: Java using scanner enter key pressed

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM