views:

49

answers:

2

Hey there, I'm searching for a Key Listener which always activates himself when the mouse is pressed down... for example if I keep pressing the button it will always write something on the console and stops writing that when I releas the mouse button.

+3  A: 

Firstly, KeyListeners respond to keyboard events: MouseListeners respond to mouse events. However if you are dealing with a JButton you probably want an ActionListener attached to the button. That will respond when the JButton is pressed, which can be in different ways, not involving the mouse.

Listeners don't generally do that sort of thing. What you need is a Timer that will write something to the console repeatedly at some interval. Then you use a ActionListener to start the process going when the button is pressed, and stop it when the button is released. The documentation for those classes should give you what you need.

DJClayworth
Timer is good. Better (more specific) than my generic Thread remark.
extraneon
+4  A: 

You could do that with a MouseListener which signals the app to start printing something on MousePressed, signals to stop printing on MouseReleased.

You should do the printing in a separate thread as to prevent the Swing GUI from freezing.

extraneon