14. 114. 5. Timer 基本动画based animation

来源:互联网 发布:matlab遗传算法代码 编辑:程序博客网 时间:2024/06/11 23:03

import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.geom.Ellipse2D;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.Timer;public class TimerBasedAnimation extends JPanel implements ActionListener{private Ellipse2D.Float ellipse = new Ellipse2D.Float();//一个精细的椭圆private double esize;private double maxSize = 0;private boolean initialize = true;//initialize:初始化Timer timer;ActionListener updateProBar;public TimerBasedAnimation(){setXY(20*Math.random(),20,20);timer = new Timer(20,this);timer.setInitialDelay(1900);//设置 Timer 的初始延迟  190毫秒timer.start();}public void setXY(double size,int w, int h){//设置xy点esize = size;//将此 Shape 窗体矩形的位置和大小设置为指定的矩形值。/*x - 指定矩形左上角的 X 坐标y - 指定矩形左上角的 Y 坐标w - 指定矩形的宽度h - 指定矩形的高度*/ellipse.setFrame(10,10,size,size);}public void reset(int w, int h){//重启方法maxSize = w;setXY(maxSize*Math.random(),w,h);}public void step(int w,int h){//设置步骤esize++;if(esize>maxSize){setXY(1,w,h);}else{ellipse.setFrame(ellipse.getX(),ellipse.getY(),esize,esize);}}public void render(int w,int h,Graphics2D g2){g2.setColor(Color.green);g2.draw(ellipse);}public void paint(Graphics g){super.paintComponent(g);Graphics2D g2 = (Graphics2D)g;RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);g2.setRenderingHints(rh);Dimension size = getSize();if(initialize){//假如为真reset(size.width,size.height);initialize = false;}this.step(size.width, size.height);render(size.width, size.height, g2);}public void actionPerformed(ActionEvent e) {repaint();    }public static void main(String[] args) {JFrame frame = new JFrame("TimerBasedAnimation");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.add(new TimerBasedAnimation());frame.setSize(350, 250);frame.setLocationRelativeTo(null);frame.setVisible(true);}}