Swing 使 JButton 无法聚焦

发布于 2024-09-18 17:12:04 字数 373 浏览 4 评论 0 原文

我想让 Java swing 按钮“不可聚焦”。 该按钮根本不应该接收焦点,但应该能够接收鼠标点击。

我想到了以下选项,但这些选项要么不能完全解决我的问题,要么看起来不够优雅。还有其他/更好/建议的选择吗?

  1. 当按钮接收焦点时,立即将焦点移动到下一个组件(但是如果按钮是 UI 上除标签之外的唯一组件,我该怎么办?)
  2. 实现另一个不可聚焦的组件作为按钮(带有鼠标事件的标签 ) ,边框...)(这对我来说看起来不太优雅)
  3. 创建一个匿名按钮实现来覆盖键盘事件,以便它不响应键盘事件(这并不能解决焦点问题,但对我来说还可以) ,因为问题的根源是为了避免意外的键盘点击,只有在根本没有选项的情况下我才会这样做,但即便如此,我还是更喜欢选项 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?

  1. 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?)
  2. Implement another non-focusable component as a button (a label with mouse events, borders...) (this does not look very elegant to me)
  3. 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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

弱骨蛰伏 2024-09-25 17:12:04

所有 Swing 组件都有一个 setFocusable 方法来执行此操作:

JButton button = ...
button.setFocusable(false);

All Swing components have a setFocusable method to do this:

JButton button = ...
button.setFocusable(false);
彼岸花ソ最美的依靠 2024-09-25 17:12:04

您是否尝试调用从 java.awt.Component 继承的 setFocusable() 方法?


资源:

Did you try to call the setFocusable() method inherited from java.awt.Component ?


Resources :

心作怪 2024-09-25 17:12:04

您可以使用与您的按钮不同的接受方法来实现您自己的 FocusTraversalPolicy(或扩展例如 ContainerOrderFocusTraversalPolicy)。

JFrame frame = new JFrame();
... /* create other components */
frame.setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy() {
    public boolean accept(Component c) {
        return super.accept(c) && c!=iDontLikeYouButton;
    }
});

You can implement your own FocusTraversalPolicy (or extend e.g. ContainerOrderFocusTraversalPolicy) with an accept method that just doesn't like your button.

JFrame frame = new JFrame();
... /* create other components */
frame.setFocusTraversalPolicy(new ContainerOrderFocusTraversalPolicy() {
    public boolean accept(Component c) {
        return super.accept(c) && c!=iDontLikeYouButton;
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文