gpt4 book ai didi

java - 用线程显示动画

转载 作者:行者123 更新时间:2023-12-02 07:59:39 26 4
gpt4 key购买 nike

我想用线程同时显示多个动画。但它不起作用,第二个动画在第一个动画结束时开始。我正在使用线程,但可能是错误的方式,因为我是初学者这是我的代码:

public class Board extends JPanel{

Mouse mouse;
ArrayList<Explosion> explosions;

public Board() {
mouse = new Mouse(this);
explosions = new ArrayList();
setDoubleBuffered(true);
this.addMouseListener(mouse);
}

public void addExplosion(Explosion e) {
explosions.add(e);
new Thread(explosions.get(explosions.indexOf(e))).start();
}

public void removeExplosion(Explosion e) {
explosions.remove(e);
}

public void paint(Graphics g) {
super.paint(g);

for(int i=0; i<explosions.size(); i++) {
explosions.get(i).paintComponent(g);
}

Graphics2D g2d = (Graphics2D)g;
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
}


public class Explosion extends JPanel implements Runnable{

private BufferedImage img;

final int width = 320;
final int height = 320;
final int rows = 5;
final int cols = 5;

private int x,y;

private int cursor;

BufferedImage[] sprites = new BufferedImage[rows * cols];

Board board;

public Explosion(Board board,int x, int y) {
this.board = board;
this.x = x;
this.y = y;

try {
try {
this.img = ImageIO.read(new File((this.getClass().getResource("files/explosion2.png")).toURI()));
} catch (URISyntaxException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}

cursor = 0;

for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sprites[(i * cols) + j] = img.getSubimage(
j * (width/rows),
i * (height/cols),
width/rows,
height/cols
);
}
}
}

public void run() {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cursor++;
}
};

Timer timer = new Timer(50, taskPerformer);

while(cursor < ((rows*cols)-1)) {
timer.start();
board.repaint();
}
timer.stop();

board.removeExplosion(this);
}

public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(sprites[cursor], x, y, this);
g.dispose();
}
}

感谢您的帮助

最佳答案

任何更新 GUI 的代码都应该在与 GUI 关联的线程上运行。要从不同的线程执行此操作,就像您的情况一样,您将需要使用 SwingUtilities.InvokeLater:

SwingUtilities.InvokeLater(new Runnable() {
public void run() {

// code to update the GUI goes here
}
});

关于java - 用线程显示动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9103228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com