0

My lecturer gave me an assignment asking for a multi threaded graphics program where a ball bounces around a jframe. He wanted each ball to have its own thread. Upon marking he told me that a timer is multi threaded and this is the best way to do this. I used a new Thread for each ball I know this is costly but he told us to use a thread for each ball. Is the timer class multi threaded?

using a timer

Ball b = new Ball(x, y);
BallMover bm = new BallMover(b)//adds the ball to a new instance of an actionListner
theTimer.addActionListener(bm);

using threads

Ball b = new Ball(x,y);
BallMover bm = new BallMover(b);//adds the ball to a new instance of a Thread
bm.start();
Harry Martland
  • 604
  • 2
  • 14
  • 26

1 Answers1

2

From the docs for the Swing Timer.

Although all Timers perform their waiting using a single, shared thread (created by the first Timer object that executes), the action event handlers for Timers execute on another thread -- the event-dispatching thread. This means that the action handlers for Timers can safely perform operations on Swing components. However, it also means that the handlers must execute quickly to keep the GUI responsive.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • so am I right in thinking that if I had 6 Balls each with there own ActionListener each actionPreformed method is running in its own thread? Thanks for the reply – Harry Martland Dec 11 '12 at 11:04
  • no issue by using only one Swing Timer and with Arrays of Balls – mKorbel Dec 11 '12 at 11:13