是否可以将 JComponent 默认设置为不可聚焦?
我知道您可以调用 JComponent.setFocusable(false)
来使 Java 组件不可聚焦。但由于我的应用程序中有很多组件我希望成为这种方式,所以我想知道是否有一种比在数十个对象中的每一个上调用它更简单的方法。就像 UIDefaults
值一样?
我正在寻找这个,因为我的应用程序全屏运行,并且 JFrame
上有一个 KeyListener
监听击键以触发各种事件。但我发现,每当单击 JButton 或其他添加的组件时,它都会获得焦点,并且关键事件永远不会到达 JFrame 。因此,一种更优雅的方式让单个父容器捕获关键事件,无论哪个子容器拥有焦点,也将有助于解决我的问题。
I know you can call JComponent.setFocusable(false)
to make a Java component not be focusable. But since I have a LOT of components in my application that I want to be that way, I was wondering if there is a simpler way than calling it on every one of dozens of objects. Like a UIDefaults
value?
I'm looking for this because my application runs full-screen and there is a KeyListener
on the JFrame
that listens for key strokes to trigger various events. But I found that whenever a JButton
or other added component is clicked it would get the focus and the key events would never reach the JFrame
. So a more elegant way to have key events be caught by a single parent container regardless of what child has the focus would also serve to fix my problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我从来没有见过一个。
不要使用 KeyListener。
相反,您可以将 JMenus 和 JMenuItems 与加速器一起使用。这种方法的好处是击键记录在菜单中。请参阅 Swing 教程中有关如何使用菜单的部分。
或者,如果您不喜欢菜单,那么您应该使用 按键绑定< /a>.即使组件没有焦点,它们也可以被编码为工作。
I've never seen one.
Don't use a KeyListener.
Instead you can use JMenus and JMenuItems with accelerators. The benefit of this approach is that the key strokes are then document in the menus. See the section from the Swing tutorial on How to Use Menus.
Or if you don't like menus, then you should be using Key Bindings. They can be coded to work even if the component doesn't have focus.
听起来像是 KeyEventDispatcher 的工作:
http://download .oracle.com/javase/6/docs/api/java/awt/KeyEventDispatcher.html
这将解决问题,而不是通过(无法计算的)副作用来修改不直接相关的属性:-)
Sounds like the job for a KeyEventDispatcher:
http://download.oracle.com/javase/6/docs/api/java/awt/KeyEventDispatcher.html
That would be solving the problem, not doctoring at not directly related properties with (incalculatable) side-effects :-)
怎么样:
然后通过以下方式调用它:
How about:
Then just call it by:
这是一种相当粗略的遍历树并将其设置在您关心的元素上的方法。只需传入一组 noFocus (或将逻辑更改为一切)...
Here is a rather crude way of walking the tree and setting it on elements you care about. Just pass in a set of noFocus (or change the logic to just be everything)...