测试 javax.swing.JButton 是否被按下

发布于 2024-12-05 13:12:21 字数 529 浏览 5 评论 0原文

我想检查某个 javax.swing.JButton (常规按钮)是否被按下(在释放之前)。有没有任何选项可以检查按钮是否按下?

最简单的解决方案是添加一个 MouseListener 来响应鼠标单击和释放事件。但是,这不包括通过 Enter 键或任何其他方式激活按钮的情况。我不想通过键盘或其他方式禁用激活鼠标 - 我只想知道何时按下鼠标而不限制其行为。

我尝试监听所有不同的事件,唯一响应按钮按下的两个事件是 ActionPreformed (ActionEvent) 和 StateChanged (ChangedEvent) 事件。 ActionPreformed 每次点击都会执行一次,这意味着仅在按下并释放按钮后执行一次,所以它不好。当我单击按钮时,StateChanged 确实被调用了几次,当我释放按钮时,StateChanged 确实被调用了几次。但是,事件对象仅包含有关源小部件(按钮)的信息,不包含有关状态更改本身的信息。这可以防止区分我们想要捕获哪些事件。

提前致谢!

I would like to check whether a certain javax.swing.JButton (regular push-button) is pressed down (before it was released). Is there any option at all to check whether a button is down?

The most trivial solution is to add a MouseListener that will respond to the mouse click and release events. But, this does not cover the case where the button was activated by the Enter key, or any other way. I don't want to disable activating the mouse by keyboards or other ways - I just want to know when is it pressed down without restricting it's behaviour.

I tried listening to all the different events, and the only two that do respond to button press are the ActionPreformed (ActionEvent) and the StateChanged (ChangedEvent) events. ActionPreformed is executed once per click, meaning only after the button was pressed and released, so it's not good. StateChanged is indeed invoked several times when I click a button, and several times when I release it. But, the event object only includes information about the source widget (the button) and no information about the state change itself. This prevents from distiguishing which of the events we want to catch.

Thanks in advance!

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

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

发布评论

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

评论(1

情话已封尘 2024-12-12 13:12:21

ButtonModel 可以做到这一点,更多 此处这里或者可能是题外话JMenuItem & ChangeListener by @kleopatra

ButtonModel can do that, more here or here or maybe off-topic JMenuItem & ChangeListener by @kleopatra

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文