测试是否按下了javax.swing.JButton [英] Test if a javax.swing.JButton is pressed down

查看:104
本文介绍了测试是否按下了javax.swing.JButton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查(松开按钮之前)是否按下了某个javax.swing.JButton(常规按钮).是否有任何选项可以检查按钮是否按下?

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?

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

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.

我尝试听所有不同的事件,并且只有两个确实响应按钮按下的事件是ActionPreformed(ActionEvent)和StateChanged(ChangedEvent)事件. ActionPreformed每次单击执行一次,这意味着仅在按下和释放按钮之后才能执行,因此效果不佳.实际上,当我单击一个按钮时,确实会多次调用StateChanged,而在释放按钮时,则会多次调用.但是,事件对象仅包含有关源窗口小部件(按钮)的信息,而没有有关状态更改本身的信息.这样可以避免混淆我们想要捕捉的事件.

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.

提前谢谢!

推荐答案

在这里此处,或者可能是主题外的 JMenuItem& @kleopatra的ChangeListener

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

这篇关于测试是否按下了javax.swing.JButton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆