2

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!

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Barak Itkin
  • 4,872
  • 1
  • 22
  • 29
  • I don't think what you're asking is provided in the JDK - the high-level events don't provide that level of detail. Your best option would be using ChangedListeners and retrieving the new state from the button. – millimoose Sep 21 '11 at 19:18
  • @Sii: That's the exact problem - how can I retreive the button state? No function seems to do that. `isSelected()` isn't used for this (and it doesn't seem to work), and I haven't found any other function. – Barak Itkin Sep 21 '11 at 19:27

1 Answers1

7

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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319