Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a swing JButton repeat its action when it is held down?

I am creating an touch screen application using Swing and have a request to change one of buttons so that it will behave like a keyboard when the button is held down.
(First of all, I am not sure that the touch screen will allow the user to "hold down" the button, but pretend that they can for now)

I was going to go down the path of starting a loop when mousePressed was called and then ending the loop when mouseReleased was called. This will involve starting a thread and having to deal with synchronization as well as invokeLater() to get events back on the EventQueue.

Is there a very simple way to do what I want? I hope I am just not seeing the API to do it.

like image 485
Tony Eichelberger Avatar asked Nov 21 '08 18:11

Tony Eichelberger


People also ask

What is toggle button in swing?

A JToggleButton is a two-state button. The two states are selected and unselected. The JRadioButton and JCheckBox classes are subclasses of this class. When the user presses the toggle button, it toggles between being pressed or unpressed. JToggleButton is used to select a choice from a list of possible choices.

What events do JButton generate?

A JButton object draws itself and processes mouse, keyboard, and focus events on its own. You only hear from the JButton when the user triggers it by clicking on it or pressing the space bar while the button has the input focus. When this happens, the JButton object creates an event object belonging to the class java.

What method is called when a user clicks a button on a Swing GUI?

The actionPerformed method is used when a button is clicked normally. If you want to do some fancy interaction with the button you can also use other events like mousePressed in the MouseListener.


2 Answers

javax.swing.Timer is your friend. And here's an article with some more info.

like image 119
ykaganovich Avatar answered Oct 31 '22 16:10

ykaganovich


I would do it like this:

  • Listen to mousePressed and schedule a java.util.Timer to be launched at a later time.
  • The Timer does the action and set itself to schedule again.
  • Listen to mouseReleased to cancel the Timer.
like image 39
Cyrille Ka Avatar answered Oct 31 '22 17:10

Cyrille Ka