Question

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!

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top