java - Making a pause (sleep) in program - does not seem to function properly? -
this question has answer here:
i have code, when user presses button, message should display on text area, , after 2~3 seconds, should disappear.
thread.sleep(milliseconds) should this, doesn't seem work (yes, have in try/catch , everything). here listener:
private class movelistener implements actionlistener { public void actionperformed(actionevent e) { cardlayout cl = (cardlayout)(cards.getlayout()); for(int = 0; < 4; i++) { for(int j = 0; j < 3; j++) { if(e.getsource() == move[i][j]) { turn++; if(turn == 4) turn = 0; text.settext(""+sprites[i]+" has used " + move[i][j].gettext() ); try { thread.sleep(3000); } catch (interruptedexception ex) { } text.settext(""); cl.show(cards, main); } } } }
when run can feel whole program freeze (probably due sleep() method), skips text.settext(themessage) , goes straight text.settext(""); in other words, should go click > display > rest > erase; click > rest > erase.
i've tried other methods: doing classic for(int = 0; < 9999999; i++) thing 20 ish times, did same thing thread.sleep() way.
any way fix this? i've read being bad use ui thread not sure meant.... appreciated.
text.settext(""+sprites[i]+" has used " + move[i][j].gettext() ); thread t = new thread(){ public void run() { try { thread.sleep(3000); } catch (interruptedexception ex) { } swingutilities.invokelater( new runnable() { text.settext(""); cl.show(cards, main); } ); } }; t.start();
the usual pattern is:
there "gui thread", or edt, or wanna call it.
the gui thread gui.
it starts new thread waits while.
in between gui thread can render other parts of gui, react on mouse, , on.
the new thread wakes , tells gui thread passing runnable object gui thread (there several methods doing so, using commonly used 1 here).
Comments
Post a Comment