用线程显示动画

时间:2012-02-01 20:56:11

标签: java multithreading swing

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

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();    
    }   
}

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

任何更新GUI的代码都应该在与GUI相关的线程上运行。要从不同的主题(例如您的情况)执行此操作,您需要使用SwingUtilities.InvokeLater

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

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