Search code examples
javaswingjbuttonbackground-colorthread-sleep

repaint function not work when event happen


i am trying to change button background color for 10 time when event happen?


private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        for (int i = 0; i < 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 the button show the 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();
}   

Solution

  • Don't call Thread.sleep(...) on the Swing event thread as this puts the entire Swing GUI to sleep. In other words, your GUI does no painting, accepts no user input or interaction at all and becomes completely useless while the event (also known as the Event Dispatch Thread or EDT). Use a Swing Timer instead. Please check out the Swing Timer Tutorial for more help on this.

    Also have a look at some of the answers to this question, including mKorbel's.