import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;

public class LoveBox extends JPanel implements Runnable {
  private int index=0;	//图片的索引
  private Thread changer;	//动态改变图片的线程，形成动画效果
  private boolean stopFlag=true;  //控制线程启动与关闭的标志
  private Image[] images; //存放献爱心图片
  private JButton contrlButton=new JButton("  开始献爱心！ ");

  public LoveBox() {

    images=new Image[5];
    //加载图片
    Toolkit tk=getToolkit();
    images[0]=tk.getImage(getClass().getResource("donate0.jpg"));
    images[1]=tk.getImage(getClass().getResource("donate1.jpg"));
    images[2]=tk.getImage(getClass().getResource("donate2.jpg"));
    images[3]=tk.getImage(getClass().getResource("donate3.jpg"));
    images[4]=tk.getImage(getClass().getResource("donate4.jpg"));
    
    contrlButton.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e){
        if(stopFlag)start();
        else stop();
    }});

    setBackground(Color.WHITE);
    setLayout(new BorderLayout());
    add(contrlButton, BorderLayout.NORTH);
  }

  public void start(){
    changer=new Thread(this);
    stopFlag=false;
    index=1;
    contrlButton.setText("  献爱心活动结束！ ");
    changer.start();
  }

  public void paint(Graphics g) {
    super.paint(g);
    if(index>-1 && index<5){
      g.drawImage(images[index],20,40,this);
      g.drawString("爱洒人间，大爱无疆",90,250);
    }
  }

  public void stop(){
    stopFlag=true;
    contrlButton.setText("  开始献爱心！ ");
  }

  public void run(){
    while(!stopFlag){
      repaint(); 
      try{
        if(index==0 || index==4)Thread.sleep(350);
        else Thread.sleep(200);
      }catch(InterruptedException e){throw new RuntimeException(e);}

      if(++index>4) index=0;   //显示下一张照片
    }

    index=0;
    repaint();  //刷新图形
  }

  public static void main(String args[]){
    JFrame gui=new JFrame("献爱心箱");
    LoveBox loveBox=new LoveBox();
 
    gui.setContentPane(loveBox);
    gui.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    gui.setSize(300,300);
    gui.setVisible( true );
  }
}


/****************************************************
 * 作者：孙卫琴                                     *
 * 来源：<<Java面向对象编程>>                       *
 * 技术支持网址：www.javathinker.net                *
 ***************************************************/
