我想让 Java swing 按钮“不可聚焦”。
该按钮根本不应该接收焦点,但应该能够接收鼠标点击。
我想到了以下选项,但这些选项要么不能完全解决我的问题,要么看起来不够优雅。还有其他/更好/建议的选择吗?
- 当按钮接收焦点时,立即将焦点移动到下一个组件(但是如果按钮是 UI 上除标签之外的唯一组件,我该怎么办?)
- 实现另一个不可聚焦的组件作为按钮(带有鼠标事件的标签 ) ,边框...)(这对我来说看起来不太优雅)
- 创建一个匿名按钮实现来覆盖键盘事件,以便它不响应键盘事件(这并不能解决焦点问题,但对我来说还可以) ,因为问题的根源是为了避免意外的键盘点击,只有在根本没有选项的情况下我才会这样做,但即便如此,我还是更喜欢选项 2)。
I want to make a Java swing button 'not-focussable'.
The button should not receive focus at all, but should be able to receive mouse clicks.
I thought the following options, but these either dont solve my problem completely, or dont seem elegant. Are there any other/better/suggested options?
- Move the focus to the next component immediately when the button receives focus (but then what do I do if the button is the only component on the UI other than labels?)
- Implement another non-focusable component as a button (a label with mouse events, borders...) (this does not look very elegant to me)
- Create a anonymous button implementation that overides the keyboard events so that it does not respond to keyboard events (this does not solve the focus problem, but is somwhat ok for me, since the root of the problem is to avoid accidental keyboard clicks. I will do this only if there are no options at all, but even then prefer option 2)
发布评论
评论(3)
所有 Swing 组件都有一个 setFocusable 方法来执行此操作:
All Swing components have a setFocusable method to do this:
您是否尝试调用从
java.awt.Component
继承的setFocusable()
方法?资源:
Did you try to call the
setFocusable()
method inherited fromjava.awt.Component
?Resources :
您可以使用与您的按钮不同的接受方法来实现您自己的 FocusTraversalPolicy(或扩展例如 ContainerOrderFocusTraversalPolicy)。
You can implement your own FocusTraversalPolicy (or extend e.g. ContainerOrderFocusTraversalPolicy) with an accept method that just doesn't like your button.