?? animatoricon.java
字號(hào):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//動(dòng)畫圖標(biāo)
public class AnimatorIcon extends JPanel implements ActionListener {
ImageIcon[] images; //用于動(dòng)畫的圖標(biāo)數(shù)組
Timer animationTimer;
int currentImage = 0; //當(dāng)前圖像編號(hào)
int delay = 500; //圖像切換延遲
int width; //圖像寬度
int height; //圖像高度
public AnimatorIcon() //構(gòu)造函數(shù)
{
setBackground(Color.white);
images = new ImageIcon[2]; //初始化數(shù)組
for (int i=0;i<images.length;i++)
images[i]=new ImageIcon(getClass().getResource("image"+i+".gif")); //實(shí)例化圖標(biāo)
width = images[0].getIconWidth(); //初始化寬度值
height = images[0].getIconHeight(); //初始化高度值
}
public void paintComponent(Graphics g) { //重載組件繪制方法
super.paintComponent(g); //調(diào)用父類函數(shù)
images[currentImage].paintIcon(this,g,70,0); //繪制圖標(biāo)
currentImage=(currentImage+1)%2; //更改當(dāng)前圖像編號(hào)
}
public void actionPerformed(ActionEvent actionEvent) {
repaint();
}
public void startAnimation() { //開始動(dòng)畫
if (animationTimer==null) {
currentImage=0;
animationTimer=new Timer(delay, this); //實(shí)例化Timer對(duì)象
animationTimer.start(); //開始運(yùn)行
} else if (!animationTimer.isRunning()) //如果沒有運(yùn)行
animationTimer.restart(); //重新運(yùn)行
}
public void stopAnimation() {
animationTimer.stop(); //停止動(dòng)畫
}
public static void main(String args[]) {
AnimatorIcon animation = new AnimatorIcon(); //實(shí)例化動(dòng)畫圖標(biāo)
JFrame frame = new JFrame("動(dòng)畫圖標(biāo)"); //實(shí)例化窗口對(duì)象
frame.getContentPane().add(animation); //增加組件到窗口上
frame.setSize(200, 100); //設(shè)置窗口尺寸
frame.setVisible(true); //設(shè)置窗口可視
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關(guān)閉窗口時(shí)退出程序
animation.startAnimation(); //開始動(dòng)畫
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -