import java.awt.Color;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

/**
 * @author Remi Forax
 *
 */
public class TimerExample {

  static Color getRandomColor() {
    return new Color(
      random.nextInt(256),
      random.nextInt(256),
      random.nextInt(256)
    );
  }
  
  private static final Random random=new Random();

  public static void main(String[] args) {
    JFrame frame=new JFrame("TimerExample");
    
    final JPanel panel=new JPanel();
    
    final Timer timer=new Timer(300,new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        for(int i=0;i<panel.getComponentCount();i++)
          panel.getComponent(i).setBackground(getRandomColor());
      }
    });
    
    final JButton timerButton=new JButton("start");
    timerButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        if (timer.isRunning())
          timer.stop();
        else
          timer.start();
          
        timerButton.setText((timer.isRunning())?"stop":"start");
      }
    });
    
    panel.add(timerButton);
    for(int i=0;i<5;i++)
      panel.add(new JButton("button "+i));
      
    frame.setContentPane(panel);
    frame.pack();
    frame.show();
  }
}
