jadrijan
jadrijan

Reputation: 1446

JTextField change value automatically while button pressed

I have a jTextField with two JButtons (Up arrow and Down arrow buttons). Clicking the Up arrow button the numeric value in the textfield increases by 1 (++), and clicking the Down arrow button the numeric value in the textfield decreases by 1 (--).

What I want know is how to automatically "scroll/change" the value while the button is pressed?

Thank you

Upvotes: 1

Views: 735

Answers (2)

Radu Murzea
Radu Murzea

Reputation: 10920

The JSpinner is the best way to do this.

But if you want a different implementation, I would suggest using a MouseListener attached to the JButtons. When one of the button is pressed (the mousePressed event), a javax.swing.Timer is started. Every x milliseconds (depending on how fast you want the number increased/decreased) a check is made to see if the JButton is still pressed and if the mouse is still over the JButton. If it is, the number is increased/decreased. When the user releases the mouse (the mouseReleased event), the Timer is stopped/cancelled.

I never did this, so I don't know for sure that it works. But this is the way I would try it.

Upvotes: 2

Sean
Sean

Reputation: 7747

What you probably want is a JSpinner. More specifically a SpinnerNumberModel.

Here is a link to a demo http://docs.oracle.com/javase/tutorial/uiswing/components/spinner.html

Upvotes: 6

Related Questions