How can I perform a task while the mouse is pressed, stopping when the mouse is released?

Scott Stanchfield

The "trick" is to create a new thread that performs the task while the normal event thread watches for the mouse release.

If you perform the mouse-pressed action inside your mousePressed() method, the event handler thread is busy; it's the one actually running your code. There's no way it can process the mouseReleased() event!

The following sample code creates a new thread to loop through printing numbers as long as the mouse is pressed. When you release the mouse, the worker thread is interrupted. The worker thread checks each time through the loop to see if it has been interrupted. If so, it stops.

import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Sample {

  Thread worker;
  class Worker extends Thread {
    int n=0;
    public void run() {
      while(true) {
        if (isInterrupted())

  public static void main(String[] args) {
    new Sample().go();

  public void go() {
    Frame f = new Frame("Sample");
    f.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
          worker = new Worker();
        public void mouseReleased(MouseEvent e) {
          if (worker != null) {
            worker = null;
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
About | Sitemap | Contact