JAVA 简单动画

来源:互联网 发布:怎么删除淘宝上的好评 编辑:程序博客网 时间:2024/05/22 03:23
package Rong;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class BounceBall extends JFrame {
 JPanel panel = new JPanel(); // 主面板
 Circle c;
 // 构造函数
 public BounceBall() {
  add(panel); // 添加面板
  panel.setLayout(null); // 设置面板的布局为空布局
  c = new Circle(panel);
  panel.add(c);
  c.setBounds(40, 140, 30, 30);
  c = new Circle(panel, Color.red);
  panel.add(c);
  c.setBounds(50, 10, 30, 30);
  // 设置窗体的属性
  this.setTitle("弹弹球");
  this.setBounds(400, 140, 400, 300);
  this.setVisible(true);
 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 //主函数
 public static void main(String[] args) {
  new BounceBall();
 }
}
class Circle extends Canvas implements ActionListener {
 private int TOP = 0; // 小球能够达到的上边界
 private int BOTTOM; // 小球能够达到的下边界
 private int LEFT = 0; // 小球能够达到的左边界
 private int RIGHT; // 小球能够达到的右边界
 private Color c; // 小球的颜色
 private int R = 30; // 小球的半径
 private int xSpeed = 8; // 小球x轴上的速度
 private int ySpeed = 7; // 小球y轴上的速度
 Timer t = new Timer(1, this); // 设置定时器
 JPanel panel;

 public void actionPerformed(ActionEvent e) { //定义事件的行为
  RIGHT = panel.getWidth();
  BOTTOM = panel.getHeight();
  Point currentPoint = this.getLocation(); //获得当前的坐标
  double x = currentPoint.getX();
  double y = currentPoint.getY();
  x = x + xSpeed;
  y = y + ySpeed;
  if ((x + R) > RIGHT || x< 0) {
   xSpeed = -xSpeed;
  }
  if (y < 0 || (y + R)> BOTTOM) {
   ySpeed = -ySpeed;
  }
  currentPoint.setLocation(x, y);
  this.setLocation(currentPoint);
 }
 public void paint(Graphics g) {
  g.setColor(c);
  g.fillOval(0, 0, R, R);
 }
 // 构造函数一:参数为要添加的面板
 public Circle(JPanel panel) {
  this.panel = panel;
  t.start();
 }
 // 构造函数二:参数为要添加的面板和颜色
 public Circle(JPanel panel, Color c) {
  this.panel = panel;
  this.c = c;
  t.start();
 }
}JAVA <wbr>简单动画