java - JFrame does't repaint -


i have jframe , has jpanel , jbutton . jframe set borderlayout , , expected code repaint panel every 500 millisecs after button has been clicked. though setup goes loop , frame not repaint.

here wrote when button clicked

public void actionperformed(actionevent e) {     while(true){         try {             frame.repaint(); // not repaint             thread.sleep(500);         } catch (interruptedexception exp) {             exp.printstacktrace();         }     } } 

and setup :

public void go() {     b.addactionlistener(new buttonlistener()); // b jbutton     frame.setdefaultcloseoperation(jframe.exit_on_close); // frame jframe     frame.setlayout(new borderlayout());     frame.add(borderlayout.center, p); // p mypanel     frame.add(borderlayout.south, b);     frame.setsize(300, 300);     frame.setvisible(true);  }  class mypanel extends jpanel { // p instance of mypanel class      public void paintcomponent(graphics gr) {         gr.fillrect(0, 0, this.getwidth(), this.getheight());          int r, g, b, x, y;         r = (int) (math.random() * 256);         g = (int) (math.random() * 256);         b = (int) (math.random() * 256);         x = (int) (math.random() * (this.getwidth() - 15 ));         y = (int) (math.random() * (this.getheight() - 15));          color customcolor = new color(r, g, b);         gr.setcolor(customcolor);         gr.filloval(x, y, 30, 30);     } } 

your actionlistener contains 2 surefire mechanisms blocking swing application - infinite loop , thread.sleep call. use swing timer instead

timer timer = new timer(500, new actionlistener() {      @override     public void actionperformed(actionevent e) {         frame.repaint();     } }); timer.setrepeats(false); timer.start(); 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -