java - repaint function not work when event happen -
i trying change button background color 10 time when event happen?
private void jbutton2actionperformed(java.awt.event.actionevent evt) { try { (int = 0; < 10; ++i) { random r = new random(); jbutton2.setbackground(new color(r.nextint(150), r.nextint(150), r.nextint(150))); jbutton2.repaint(); thread.sleep(200); } } catch (exception e) { system.out.println(e.tostring()); } }
but button show last color??
thanks it's work correctly
int x = 0; timer timer; private void jbutton2actionperformed(java.awt.event.actionevent evt) { timer = new timer(1000, new actionlistener() { @override public void actionperformed(actionevent e) { random r = new random(); jbutton2.setbackground(new color(r.nextint(150), r.nextint(150), r.nextint(150))); jbutton2.repaint(); if(x==10){ timer.stop(); x=0; } else{ x++; } } }); timer.start(); }
don't call thread.sleep(...) on swing event thread puts entire swing gui sleep. in other words, gui no painting, accepts no user input or interaction @ , becomes useless while event (also known event dispatch thread or edt). use swing timer instead. please check out swing timer tutorial more on this.
also have @ of answers this question, including mkorbel's.
Comments
Post a Comment