java多线程图片动画
时间: 2023-10-05 20:10:14 浏览: 111
Java多线程图片动画可以使用Java Swing中的JPanel和JLabel实现。下面是一个简单的示例代码:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
public class ImageAnimation extends JPanel implements ActionListener, Runnable {
private JLabel imageLabel;
private BufferedImage[] images;
private Timer timer;
private int currentImageIndex = 0;
private Thread thread;
public ImageAnimation() {
setLayout(new BorderLayout());
images = new BufferedImage[10];
for (int i = 0; i < 10; i++) {
images[i] = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = images[i].createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 100, 100);
g2d.setColor(Color.BLACK);
g2d.fillOval(i * 10, i * 10, 100 - i * 20, 100 - i * 20);
g2d.dispose();
}
imageLabel = new JLabel(new ImageIcon(images[0]));
add(imageLabel, BorderLayout.CENTER);
timer = new Timer(100, this);
timer.start();
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop() {
if (thread != null) {
thread.interrupt();
thread = null;
}
}
@Override
public void actionPerformed(ActionEvent e) {
currentImageIndex = (currentImageIndex + 1) % images.length;
imageLabel.setIcon(new ImageIcon(images[currentImageIndex]));
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
currentImageIndex = (currentImageIndex + 1) % images.length;
imageLabel.setIcon(new ImageIcon(images[currentImageIndex]));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Image Animation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
ImageAnimation animation = new ImageAnimation();
frame.add(animation);
frame.setVisible(true);
animation.start();
}
}
```
在这个示例中,我们创建了一个JPanel,将其布局设置为BorderLayout,并在其中添加了一个JLabel用于显示图片。我们使用BufferedImage数组存储10个不同的图片,并使用Graphics2D绘制不同的图形。在构造函数中,我们还创建了一个Swing Timer用于更新显示的图像。在actionPerformed()方法中,我们更新当前显示的图像,以便在每个计时器周期内显示下一个图像。在run()方法中,我们创建了一个单独的线程来不断更新显示的图像,以便创建一个动画效果。最后,在main()方法中,我们创建了一个JFrame并将ImageAnimation组件添加到其中,然后启动动画。
阅读全文