在添加另一个带有 5 个 JLabels
的 JPanel
时,我遇到了 Java KeyListener
的问题,我已经在这个网站上进行了搜索,此问题的大多数解决方案都涉及从 KeyListener
切换到 KeyBindings
。这对我来说不起作用,因为我需要确切地知道何时按下、释放和按住某个键。据我所知,KeyBindings
并未提供所有这些。
我尝试过使用
this.requestFocus();
创建新的 JPanel
后,它不起作用,但是当我在 paintComponent()
中使用同一行时,它起作用了。这让我想到了我的问题:这对性能有何影响?我的 paintComponent()
被调用大约 60 次/秒。有没有办法调用一次并且仍然可以正常工作?我发现 JComponent
类型中的 requestDefaultFocus()
已被弃用...
我还尝试将相同的 KeyListener 添加到第二个 JPanel,但这没有帮助。我猜其中一个 JLabel 是获得焦点的那个?
最佳答案
This wont work for me because I need to know exactly when a key is pressed, released and held down. To my knowledge, KeyBindings does not provide all those.
是的,确实如此。您有一个“按下”和“释放”的操作。不存在“按住”这样的操作(即使对于 KeyListener 也是如此),您只会生成多个事件。
this.requestFocus();
这不是将请求焦点用于组件的正确方法。阅读该方法的 API,它会告诉您要使用的正确方法。
however when I use the same line inside the paintComponent(), it works.
这是因为在框架实现之前,您无法请求对组件的焦点,这意味着您已经在框架上调用了 pack() 或 setVisible()。
Is there a way to call it once and still have this working?
请参阅 Dialog Focus 中的 RequestFocusListener
类.
正确的解决方案是使用键绑定(bind),这样您就不需要使用这些解决方法。
关于具有多个 JPanel 的 Java keyListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17093883/