简体   繁体   中英

KeyListener not working using Applet

I have an applet using a keylistener, but the events are not triggered when I press the keys.. I also add the setFocusable(true), but didn't work too..

Here is my code

http://pastebin.com/WnFVVps7

I am creating a new KeyListener and adding it to the applet object. Also I am using setFocusable(true) on my init() method.

I don't know what to do more, can someone take a look at my code? thanks.

Thanks alot in advance ;)

This is common issue with KeyListener .

The problem is, KeyListener will only respond to key strokes when the component it is registered to is focusable AND has keyboard focus. This, generally, makes it inappropriate for general use, it's really a specialised listener.

Instead, you should use the Key Bindings API , which allows you to control the focus level that the key strokes will be triggered at

If you want to catch global key events for the application instead of just for a component, use KeyEventPostProcessor . This should be used carefully.

I have not tried it, but maybe the problem is that you declare a class KeyListener and also import another class by that name. Try renaming your KeyListener-class to something less generic.

Also: Are you sure the class KeyListener should implement KeyAdapter and not java.awt.event.KeyListener?

Do KeyListener.keyReleased() and .keyTyped() work?

There was a while(true) with Thread sleep inside it. The keystrokes were not triggered because of that, I changed the code to start the while(true) inside a new Thread and works now :)

Thanks all for your patience ;)

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