Animação

1 resposta
sammaraAdriana

Por que as imagens não estão carregando?

import javax.swing.JPanel;
import javax.swing.ImageIcon;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class LogoAnimatorJPanel extends JPanel
{
    private final String IMAGE_NAME="attack";
    protected ImageIcon images[];
    private final int TOTAL_IMAGES=8;
    private int currentImage=0;
    private final int ANIMATION_DELAY=50;
    private int width,height;
    private Timer animationTimer;

    public LogoAnimatorJPanel()
    {
        images=new ImageIcon[TOTAL_IMAGES];

        for (int i=0;i<images.length;i++)
            images[i]=new ImageIcon(getClass().getResource(IMAGE_NAME+i+".bmp"));

        width=images[0].getIconWidth();
        height=images[0].getIconHeight();
    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        images[currentImage].paintIcon(this, g, 0,0);

        if(animationTimer.isRunning())
            currentImage=(currentImage+1)%TOTAL_IMAGES;
    }
    public void startAnimation()
    {
        if(animationTimer==null)
        {
            currentImage=0;

            animationTimer=new Timer(ANIMATION_DELAY,new TimerHandler());

            animationTimer.start();
        }
        else
        {
            if(!animationTimer.isRunning())
                animationTimer.restart();
        }
    }
    public void stopAnimation()
    {
        animationTimer.stop();
    }
    public Dimension getMinimumSize()
    {
        return getPreferredSize();
    }
    public Dimension getPreferredSize()
    {
        return new Dimension(width,height);
    }
    private class TimerHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            repaint();
        }
    }
    
}

Aplicativo

import javax.swing.JFrame;

public class LogoAnimatorJPanelTest extends JFrame
{
    public static void main(String args[])
    {
         LogoAnimatorJPanel animation=new LogoAnimatorJPanel();
         JFrame f=new JFrame("Animator Test");
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.add(animation);
         f.pack();
         f.setVisible(true);
         animation.startAnimation();
    }
}

1 Resposta

Marky.Vasconcelos

Voce podia carregar diretamente BufferedImages invés desses ImageIcons, da uma olhadinha em “O Loop de Animação”.

Criado 26 de novembro de 2010
Ultima resposta 26 de nov. de 2010
Respostas 1
Participantes 2