/*Ball.java(显示跳动的小球)*/
import java.awt.event.*;
import javax.swing.Timer;
import java.awt.*;
import javax.swing.*;

public class Ball extends JPanel implements ActionListener {
  private int delay=10;
  protected Timer timer=new Timer(delay,this);
  private int x=0;private int y=0;  /*球的起始位置*/
  private int radius=15;            /*球的半径*/
  private int dx=2;                 /*球的横向增量*/
  private int dy=2;                 /*球的纵向增量*/

  public Ball(){
    timer.start();
  }

  public void actionPerformed(ActionEvent e) {
    repaint();
  }

  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.red);
    /*检查球的边界*/
    if(x<radius)  dx=Math.abs(dx);
    if(x>getWidth()-radius)  dx=-Math.abs(dx);
    if(y<radius)  dy=Math.abs(dy);
    if(y>getHeight()-radius)  dy=-Math.abs(dy);
    /*调整球的位置*/
    x+=dx;
    y+=dy;
    g.fillOval(x-radius,y-radius,radius*2,radius*2);
  }

  public void suspend() {
    timer.stop();             /*暂停时钟*/
  }

  public void resume() {
    timer.start();            /*激活时钟*/
  }

  public void setDelay(int delay) {
  this.delay=delay;
    timer.setDelay(delay);
  }
}