Java: repaint() not working? -


code:

@override     public void mousereleased(mouseevent e) { //when mouse pressed         point where=e.getpoint();         int x=(where.x-3)/20+1;         int y=(where.y-30)/20+1;         if(x>=1&&x<=30&&y>=1&&y<=30)         {             v[x][y]=1-v[x][y];             repaint();             try{             timeunit.milliseconds.sleep(300);             }             catch(exception ex){}             redo();             repaint();         }     } 

the paint function made show, on screen, 30x30 elements of v matrix. redo function makes changes (the details irrelevant) v.

what trying paint elements of v, v[x][y] changed, wait 0.3s, , paint elements of v again, time after changed redo function. repaint works second time, first time not doing anything.

the sleep block event driven thread (edt) - try not sleep in main thread of application. edt render frames / dialogs / panels, , respond clicks , menus , keyboard entry. it's important quick tasks on thread.

how adding timer object run code later?

  timer timer = new timer(300, new actionlistener(){       @override      public void actionperformed(actionevent e) {          swingutilities.invokelater(new runnable() {             @override             public void run() {                // runs code on edt edit ui elements (recommended way)                redo();                repaint();             }           });        }   });   timer.setrepeats(false);   timer.start(); 

so timer object create new thread, delay 300 milliseconds, , call 'actionperformed' method. happen on timer's thread. it's not recommended change ui elements thread except edt, use invokelater method causes swing run runnable on edt - on original thread.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -