Fire a JButton with spacebar, or enter key, or mouse click

前端 未结 2 927
我寻月下人不归
我寻月下人不归 2020-12-19 21:25

I\'m trying to get a simple JFrame with a single button to fire an event when any of these events happen:

  • The Enter key is pressed AND the JButton has focus
相关标签:
2条回答
  • 2020-12-19 22:02

    BasicButtonListener, used by BasicButtonUI, ensures that all buttons (check, radio, toggle) are bound to Space when focused. This works across platforms, even though individual Look & Feels may render various button model states uniquely. Pressing Space evokes the pressed UIAction, and releasing Space evokes the released UIAction. The same occurs when the mouse is pressed and released within the button's bounds; drag outside the button while pressed to see the armed state change.

    In either case, the combination of pressed and released invokes your button's actionPerformed() method.

    One convenient way to bind Enter to an Action, irrespective of focus, is via the root pane's setDefaultButton() method. This example illustrates all three ways to click a button.

    0 讨论(0)
  • 2020-12-19 22:03

    What you can (and probably should) do is create an AbstractAction. You can use the AbstractAction both for your ActionMap as well as for clicking (do JButton.setAction(...))

    0 讨论(0)
提交回复
热议问题