why keylistener doesn't work java

The problem is, most likely, the applet doesn't have keyboard focus. This is a common issue with KeyListener.

While you have set the applet as being focusable, it doesn't mean that the applet has keyboard focus.

You could try using requestFocusInWindow, but this may not work as expected in applets. You could also add a MouseListener to the applet, so that when the user clicks on the applet, you would requestFocusInWindow to ensure that the applet has keyboard focus

I would recommend, instead, if you have to develop an applet, you try using JApplet. Instead of painting directly to the applet itself, I'd recommend that you use a custom component, say something like, JPanel, and override its paintComponent method instead.

Apart from providing flexibility in regards to the deployment of the component, it's also double buffered.

Don't forget to call super.paintXxx

Also, this would also allow you to use the key bindings API which has the ability to overcome many of the shot comings of the KeyListener

reflink: https://stackoverflow.com/questions/19339781/why-doesnt-the-keylistener-work

 

For receives key events on JPanel you must set focus:

setFocusable(true);
requestFocus(); 

the JPanel now has focus, so it receives key events

reflink: https://stackoverflow.com/questions/16530775/keylistener-not-working-for-jpanel

https://www.daniweb.com/programming/software-development/threads/384681/keylistener-not-working

 

  • Call super.paintComponent (not related to you question, but will solve some issues later on)
  • Make the component "focusable" - Component#setFocusable
  • Use key bindings over KeyListener
  • Use Component#requestFocusInWindow over Component#requestFocus...

From the Java Docs

Because the focus behavior of this method is platform-dependent, developers are strongly encouraged to use requestFocusInWindow when possible

reflink: https://stackoverflow.com/questions/13354230/keylistener-not-working

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值