Using Threads with Buttons in Java

Introduction

If you use Thread.sleep() to pause in a repetitive process inititiated by a button, the pause will not take effect at the proper time. To have the pause() operate properly, you have to start another thread. One way of doing this is with an anonymous inner class -- it follows directly after Thread() below:

Thread  advanceThread = new Thread()	
{		
      public void run()
      {					           
	   findStart();
      }
};
advanceThread.start();

In the anonymous inner class, we write our own version of run() which overrides the run method of class Thread. In run() we call the method that contains the pause(), here findStart(). We then call the start() method of Thread. The entire code given above should be placed in the scope of the actionPerformed method of the button class that implements ActionListener.


Samuel Marateck
SAT Jan 20 22:23:14 EST 2007