📄 animatordemo.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AnimatorDemo extends JFrame implements ActionListener
{
private AnimatorPanel animatorPanel; //绘制动画的面板
private JButton startButton, stopButton;
private JPanel buttonPanel; //存放开始按钮和结束按钮的面板
public AnimatorDemo()
{
super("getImage");
setSize(400, 400);
//获取内容面板
Container container = getContentPane();
//创建用于绘制图像的面板
animatorPanel = new AnimatorPanel();
container.add(animatorPanel, BorderLayout.CENTER);
//创建按钮
startButton = new JButton("开始");
stopButton = new JButton("停止");
stopButton.setEnabled(false);
//设置字体
Font font = new Font("Serif", Font.PLAIN, 14);
startButton.setFont(font);
stopButton.setFont(font);
//注册监听器
startButton.addActionListener(this);
stopButton.addActionListener(this);
//创建存放开始和停止按钮的面板
buttonPanel = new JPanel();
buttonPanel.add(startButton);
buttonPanel.add(stopButton);
container.add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//处理按钮事件
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == startButton)
animatorPanel.start();
else if(event.getSource() == stopButton)
animatorPanel.stop();
}
public static void main(String[] args)
{
AnimatorDemo application = new AnimatorDemo();
}
class AnimatorPanel extends JPanel implements ActionListener
{
private ImageIcon images[];
private int currentImage = 0; //当前帧
private Timer timer; //定时器
private int x = -100, y; //图像的坐标
public AnimatorPanel()
{
super();
setBackground(Color.WHITE);
images = new ImageIcon[4]; //创建图像对象数组
for(int i = 0; i < images.length; i++)
{ //载入图像
images[i] = new ImageIcon("boy0" + (i+1) + ".png");
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2d=(Graphics2D)g;
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
//绘制图像,坐标为屏幕中心
y = (this.getHeight() - images[currentImage].getIconHeight())/2;
images[currentImage].paintIcon(this, g, x, y);
//定时器正在运行
currentImage = (++currentImage)%4;
}
//开始动画
public void start()
{
if(timer == null)
{
currentImage = 0;
timer = new Timer(100, this); //创建定时器
timer.start();
}
else if(!timer.isRunning())
timer.restart();
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
//动画暂停
public void stop()
{
timer.stop();
startButton.setEnabled(true);
stopButton.setEnabled(false);
}
//处理定时器事件
public void actionPerformed(ActionEvent event)
{
x += 10;
if(x >= 450)
x = -100;
repaint();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -