anim2.java

来自「刘艺编著的java教程的课本习题加例题代码 很有用哦!」· Java 代码 · 共 63 行

JAVA
63
字号
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Anim2 extends JPanel implements ActionListener {

   protected ImageIcon imag[];       // 声明图像数组

   protected int totalImag = 10,       // 声明图像文件数
                 curImag = 0,      // 当前图像文件索引
                 animDelay = 50,   // 毫秒延迟时间
                 width,           // 图像宽度
                 height;          // 图像高度

   protected String imagName = "T";  // 基图像名
   protected Timer animTimer;       // 定义驱动动画的时钟

   public Anim2(){
      initAnim();
   }

   public Anim2(int count, int delay, String name){
      totalImag=count;
      animDelay=delay;
      imagName=name;
      initAnim();
   }

   // 动画初始化
   protected void initAnim(){
      imag = new ImageIcon[ totalImag ];     // 声明ImageIcon类的引用数组

      // 装载图像
      for ( int count = 1; count <= imag.length; ++count )
         imag[ count-1 ] = new ImageIcon( getClass().getResource(
            "images/" + imagName + count + ".gif" ) );
 
      width = imag[ 0 ].getIconWidth();         // 获取图像宽度
      height = imag[ 0 ].getIconHeight();        // 获取图像高度
   }

   public void paintComponent( Graphics g ) {    // 显示当前图像
      super.paintComponent( g );

      imag[ curImag ].paintIcon( this, g, 0, 0 );
      curImag = ( curImag + 1 ) % totalImag;
   }

   public void actionPerformed( ActionEvent e ){      // 时钟事件
      repaint();  
   }

   public void startAnim() {						  // 启动动画
         curImag = 0;  
         animTimer = new Timer( animDelay, this );
         animTimer.start();
  }
   
   public void stopAnim(){         // 终止时钟
       animTimer.stop();
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?