java - Simple animation using Thread.sleep() in ActionListener -


i'm having trouble code using create roulette wheel. goal spin wheel when click "spin!" button. have done creating loop should change status of wheel true false, changes orientation. this, when done fast enough, should create illusion of movement.

the problem having: wheel repainting after whole loop done, despite placement of repaint(). so, spins 1 tick.

here sample code of actionlistener:

public class spinlistener implements actionlistener {     roulettewheel wheel;     int countend = (int)(math.random()+25*2);     public spinlistener(roulettewheel w)     {         wheel = w;     }     public void actionperformed(actionevent e)     {         (int = 0; <countend; i++)         {             try              {                 thread.sleep(100);                 if (wheel.getstatus() == true)                 {                     wheel.setstatus(false);                     repaint();                 }                 if (wheel.getstatus() == false)                 {                     wheel.setstatus(true);                     repaint();                 }             }              catch (interruptedexception ex)              {                 logger.getlogger(wheelbuilder.class.getname()).log(level.severe, null, ex);             }         }     } } 

update: figured out problem. here changes made having similar problem.

public class spinlistener implements actionlistener {     timer tm = new timer(100, this);     int count = 0;      public void actionperformed(actionevent e)     {         tm.start();         changewheel();     }     public void changewheel()     {         int countend = (int)(math.random()+20*2);         if (count < countend)         {             wheel.setstatus(!wheel.getstatus());             repaint();             count++;         }     } } 

swing single threaded environment, blocks event dispatching thread, prevent been able process new events, including, paint events.

the use of thread.sleep within actionperformed method blocking edt, preventing processing new events, including paint events, until actionperformed method exited.

you should use javax.swing.timer instead.

take @ concurrency in swing , how use swing timers more details


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -