简体   繁体   中英

JButton action Listener

嘿,我正在寻找一个按键侦听器,该按键侦听器总是在按下鼠标时激活自己……例如,如果我一直按下该按钮,它将始终在控制台上写东西,而当我释放鼠标按钮时,它会停止写东西。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM