java - using sleep() in swing -


public class testframe extends jframe {    public testframe()    {          setbounds(10, 10, 500, 500);         setlocationrelativeto(null);         setdefaultcloseoperation(3);           }     public static void main(string[] args) throws interruptedexception    {         testframe tf = new testframe();         tf.add(new jbutton("test1"));         tf.setvisible(true);         thread.sleep(2000);         tf.getcontentpane().removeall();         tf.add(new jbutton("test2"));         system.out.print("show test");    } } 

i want program show jbutton("test2") after 2 seconds.
add thread.sleep(2000) after test1.

but don't know why program stops @ showing test1 jbutton, not showing test2 jbutton , "show test" message can sucess print out

short answer, don't.

swing single threaded framework, means thing blocks event dispatching thread prevent updating ui or processing new events (making ui it's hung, cause has).

sure, use thread, swing not thread safe. means modifications ui must made within context of event dispatching thread. while there ways overcome this, easiest way use swing timer.

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

you should take @ initial threads.

when updating ui, may required call revaldiate , repaint after have added new components force ui update re-layout it's contents.


Comments

Popular posts from this blog

cookies - Yii2 Advanced - Share session between frontend and mainsite (duplicate of frontend for www) -

angular - password and confirm password field validation angular2 reactive forms -

php - Permission denied. Laravel linux server -