Animated .gif in JPanel

Hello,
I'm trying to render an animated .gif in a JPanel. I'm overriding paintComponent as follows:
   public void paintComponent(Graphics g)
      super.paintComponent(g);
      // center the background image.
      //backgroundImage is an Image
      if (backgroundImage != null)
         g.drawImage(backgroundImage, (this.getWidth() - backgroundImage
               .getWidth(this)) / 2, (this.getHeight() - backgroundImage
               .getHeight(this)) / 2, this);
   }The problem: I'm only getting the first frame displayed. What do I need to do to properly display the animated image?
Thanks.
Marc

Adding a JLabel is not convenient, nor is it the proper way to do it. The panel has other components and coming up with a layout manager that will overlay components is not the proper thing to do.
Creating a Thread is also not the proper thing to do.
I found a solution that works fine. Instead of using an Image, I create an ImageIcon and use that to display the animated gif.
   public void paintComponent(Graphics g)
      super.paintComponent(g);
      // center the background image.
      // backgroundImage is an ImageIcon
      if (backgroundImage != null)
         g.drawImage(backgroundImage.getImage(), (this.getWidth() - backgroundImage
               .getIconWidth()) / 2, (this.getHeight() - backgroundImage
               .getIconHeight()) / 2, this);
   }Thanks for your help.

Similar Messages

  • Animated GIF Image on a JPanel.

    How can I display an animated GIF image on a JPanel? It should animate after displaying.
    Regards

    I think this code should display an animated GIF image on a JPanel.
    -Mani
    import javax.swing.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.*;
    public class Animation {
    public static void main(String args[]) {
    JLabel imageLabel = new JLabel();
    JLabel headerLabel = new JLabel();
    JFrame frame = new JFrame("JFrame Animation");
    JPanel jPanel = new JPanel();
    //Add a window listner for close button
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    // add the header label
    headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
    headerLabel.setText("Animated Image!");
    jPanel.add(headerLabel, java.awt.BorderLayout.NORTH);
    //frame.getContentPane().add(headerLabel, java.awt.BorderLayout.NORTH);
    // add the image label
    ImageIcon ii = new ImageIcon("d:/dog.gif");
    imageLabel.setIcon(ii);
    jPanel.add(imageLabel, BorderLayout.CENTER);
    frame.getContentPane().add(jPanel, java.awt.BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

  • Resized animated gif ImageIcon not working properly with JButton etc.

    The problem is that when I resize an ImageIcon representing an animated gif and place it on a Jbutton, JToggelButton or JLabel, in some cases the image does not show or does not animate. More precicely, depending on the specific image file, the image shows always, most of the time or sometimes. Images which are susceptible to not showing often do not animate when showing. Moving over or clicking with the mouse on the AbstractButton instance while the frame is supposed to updated causes the image to disappear (even when viewing the non-animating image that sometimes appears). No errors are thrown.
    Here some example code: (compiled with Java 6.0 compliance)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              new Test();
         static final int  IMAGES        = 3;
         JButton[]           buttons       = new JButton[IMAGES];
         JButton             toggleButton  = new JButton("Toggle scaling");
         boolean            doScale       = true;
         public Test()
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel(new GridLayout(1, IMAGES));
              for (int i = 0; i < IMAGES; i++)
                   p.add(this.buttons[i] = new JButton());
              f.add(p, BorderLayout.CENTER);
              f.add(this.toggleButton, BorderLayout.SOUTH);
              this.toggleButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e)
                        Test.this.refresh();
              f.setSize(600, 300);
              f.setVisible(true);
              this.refresh();
         public void refresh()
              this.doScale = !this.doScale;
              for (int i = 0; i < IMAGES; i++)
                   ImageIcon image = new ImageIcon(i + ".gif");
                   if (this.doScale)
                        image = new ImageIcon(image.getImage().getScaledInstance(180, 180, Image.SCALE_AREA_AVERAGING));
                   image.setImageObserver(this.buttons);
                   this.buttons[i].setIcon(image);
                   this.buttons[i].setSelectedIcon(image);
                   this.buttons[i].setDisabledIcon(image);
                   this.buttons[i].setDisabledSelectedIcon(image);
                   this.buttons[i].setRolloverIcon(image);
                   this.buttons[i].setRolloverSelectedIcon(image);
                   this.buttons[i].setPressedIcon(image);
    Download the gif images here:
    http://djmadz.com/zombie/0.gif
    http://djmadz.com/zombie/1.gif
    http://djmadz.com/zombie/2.gif
    When you press the "Toggle scaling"button it switches between unresized (properly working) and resized instances of three of my gif images. Notice that the left image almost never appears, the middle image always, and the right image most of the time. The right image seems to (almost) never animate. When you click on the left image (when visble) it disappears only when the backend is updating the animation (between those two frames with a long delay)
    Why are the original ImageIcon and the resized ImageIcon behaving differently? Are they differently organized internally?
    Is there any chance my way of resizing might be wrong?

    It does work, however I refuse to use SCALE_REPLICATE for my application because resizing images is butt ugly, whether scaling up or down. Could there be a clue in the rescaling implementations, which I can override?
    Maybe is there a way that I can check if an image is a multi-frame animation and set the scaling algorithm accordingly?
    Message was edited by:
    Zom-B

  • Animated GIF frame loss

    I have an applet that has a JPanel with a JLabel in it. That JLabel was created with an ImageIcon constructor with an animated gif image. The gif has eleven frames (each with replace set) and is set to loop. When I bring up the applet the image animates through the first 7 frames then stops. I can File/Open the gif in Netscape and it looks fine - animates all images and loops. Looking at it with:
    setDebugGraphicsOptions(DebugGraphics.BUFFERED_OPTION); or FLASH_OPTION
    it looks good until that 7th frame then I start to see flash of grey the size of the JLabel.
    I understand that the ImageObserver defaults to the JLabel. But I have tried directly setting it with no joy. I have also tried calling .flush() on the image with no joy. So I tried a different animated gif and it stopped on the 3rd frame (but also appears fine in a browser).
    I am on day 2 of trying to figure this out (pulling my hair out).
    I cut this down quite a bit, so there may be syntax errors.
    public class RRR extends JApplet implements RRRConsts
    public void init()
    loadImages();
    myJPanel = new MyJPanel();
    contentPane.add(myJPael);
    private void loadImages()
    try
    problemImage = loadImage(new URL(getDocumentBase(),
    "problem.gif"));
    catch (Exception e)
    { logger.log(Level.SEVERE, "Unable to load images", e); }
    private Image loadImage(URL url) throws InterruptedException
    Image image = getImage(url);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(image, 0);
    tracker.waitForID(0);
    return image;
    MyJPanel myJPanel = null;
    static Image problemImage = null;
    class MyJPanel extends JPanel implements RRRConsts
    MyJPanel()
    setLayout(null);
    setBounds(0,0,468,540);
    setOpaque(false);
    buildUI();
    private void buildUI()
    myLabel = new MyLabel();
    add(myLabel);
    private MyLabel myLabel = null;
    class MyLabel extends JLabel implements RRRConsts, ActionListener
    MyLabel()
    super(new ImageIcon(RRR.problemImage));
    }

    I just had the same problem. It seems that when using an animated gif as ImageIcon it will not be loaded compeltly if it is too large. The maximum seems to be somewhere between 60 - 70 KB.
    I managed to use a higher compression on my gifs to make them smaller, but I haven't found any general solution yet.

  • Problems playing animated gif on label again

    I have program that is displaying a graphic representation of a wave file this is a cut down of it. I am using a mouse listener to detect the mouse wheel and from that I am zooming in on the wave graphic or zooming out.
    The problem is when I zoom in a Jlabel is displayed with an animated gif saying �zooming in� that work fine. But as soon as I zoom in again, the Jlabel will not display the image again or the zooming out image.
    I an new to java so be kind to my code
    Any help would be greatly appreciated
    CODE
    * DisWav1.java
    * Created on 30 April 2006, 14:43
    import java.awt.BasicStroke;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Line2D;
    import java.util.Vector;
    import javax.swing.JPanel;
    import javax.swing.JDialog;
    public class DisWav1 extends JDialog implements Runnable{
    // varables
         private Thread thread;
         public static final int MAX_PRIORITY = 10;
         Vector lines = new Vector();
         Color jfcBlue = new Color(204, 204, 255);
    Color pink = new Color(255, 175, 175);
    private Font font12 = new Font("serif", Font.PLAIN, 12);
    long mainSize = 36000;
    int holdingArray[];
    int ZOOMFactor;
         private JPanel jContentPane = null;
         * This is the default constructor
         public DisWav1() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setBackground(java.awt.Color.black);
              this.setContentPane(getJContentPane());
              this.setTitle("Display Wave");
    this.setSize(150,150);
    addMouseWheelListener(new java.awt.event.MouseWheelListener() {
    public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
    formMouseWheelMoved(evt);
         * This method initializes jContentPane
         * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setBackground(java.awt.Color.black);
                   jContentPane.setLayout(new BorderLayout());
              return jContentPane;
         public void run()
    }// end run
    public void start() {
    thread = new Thread(this);
    thread.setName("Display Graph");
    thread.setPriority(MAX_PRIORITY );
    thread.start();
    }// end start
    public void stop() {
    if (thread != null) {
    thread.interrupt();
    thread = null;
    }// end stop
    // Create a array for drawing ines on screen in scale.
    public void moveMe(int x, int y){
    this.setLocation(x,y);
    // used to detect when the mouse is wheel is move and then
    // zoom IN or OUT
    // also display jLabel with animated gif saying "zooming in" or "Zooming out"
    private void formMouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
    javax.swing.JLabel zz;
    zz = new javax.swing.JLabel();
    zz.setBounds(this.getWidth()/2, this.getHeight()/2, 140,40);
    zz.setText("");
    getContentPane().add(zz);
    int notches = evt.getWheelRotation();
    if (notches < 0) {
    getContentPane().add(zz);
    zz.setIcon(new javax.swing.ImageIcon("zoomingin.gif"));
    zz.setBounds(this.getWidth()/2-(zz.getWidth()/2), this.getHeight()/2-(zz.getHeight()/2), 140,40);
    System.out.println("zoom up " + ZOOMFactor);
    ZOOMFactor = ZOOMFactor +2;
    } else {
    if (ZOOMFactor <= 0 )
         ZOOMFactor = 1;
    else{
    getContentPane().add(zz);
    zz.setIcon(new javax.swing.ImageIcon("C:zoomingOUT.gif"));
    zz.setBounds(this.getWidth()/2-(zz.getWidth()/2), this.getHeight()/2-(zz.getHeight()/2), 140,40);
    ZOOMFactor = ZOOMFactor - 2;
    System.out.println("zoom down " + ZOOMFactor);
    public void paint(Graphics g) {
    // paints lines form a vector here on the screen
    }// end of paint method
    }// end class disWav1
    // END CODE

    think ive solved it

  • Animated gif layered above background image

    I have a static background image which is displayed in a JPanel. I need to display animated gifs at certain positions on the base image. For every new frame of the animation, the paint method is called whcih attempts to load the entire base image + all the new animated images which is extremely slow!. It also means the animated gif keeps on getting loaded, and seldom gets beyond the first frame.
    Im sure many people have had to do something like this. Is the solution to draw the gifs on the glasspane (or use layered panes), and to have a seperate paint method? or is their a simple approach like setting a special clip area.

    thanks for the help...
    The size of the background image is approx 400*400 pixels (gif or jpg), and the icons are 25*25, and have between 1 and 6 frames.
    Here comes the code... I havent finished with the mediatracker stuff, but youll get the idea Im sure.
      public void paint(Graphics g) {
        MediaTracker tracker = new MediaTracker(this);
        tracker.addImage(image,0);
        try {tracker.waitForID(0);}
        catch (InterruptedException e){}
        g.drawImage(image, 0, 0, this); //draw background image (approx 400*400 pixels)
        int ICON_ID = -1;
        Image img;
        //draw all the icons...
        //all icons have between 1 and 6 frames. 25*25 pixels.   
        for (int i = 0; i < icon_IDs.size(); i++) {
          try {
            ICON_ID = new Integer(icon_IDs.elementAt(i).toString()).intValue();
            Point p = dm.getIconPosition(ICON_ID);
            if (isAlarm(ICON_ID)) {        //ITS AN ALARM - use animated gif
              img = getAlarmImage(ICON_ID);
            else                          //NORMAL ICON - no animation
              img = DataDefinition.getImageIcon(dm.getIconType(ICON_ID)).getImage();
            tracker.addImage(img,0);
            try {tracker.waitForID(0);}
            catch (InterruptedException e){}
            int width = DataDefinition.getSize(dm.getIconType(ICON_ID)).width;
            int height = DataDefinition.getSize(dm.getIconType(ICON_ID)).height;
            g.setClip(p.x, p.y, p.x+width, p.y+height);
            g.drawImage(img, p.x, p.y, p.x+width, p.y+height, 0,0,img.getWidth(this),img.getHeight(this),this);
          catch (SQLException sqle) {
            System.out.println("Could not find position of icon : " + ICON_ID);
      }

  • Animated gif on createCustomCursor

    Hello All,
    I am trying to show an animated gif on one of my custom cursors using :
    Toolkit tk = Toolkit.getDefaultToolkit();
    try{
    myFrame.setCursor(
    tk.createCustomCursor(ImageIO.read(this.getClass().getResourceAsStream("test.gif")),new Point(15,15),"MyCursor" ) );
    catch(Exception e){}But i always see a static image for that gif.
    And when i try to use the same Image to show it on a JLabel something like this :
    ImageIcon ii = new ImageIcon(this.getClass().getResource("test.gif"));
    JLabel label3 = new JLabel(ii);I see the animated image here.
    Can someone help in showing the animated gif on the customcursor.
    I have tried using the below discussion for reference but it didnt help for animated images.
    http://forums.sun.com/thread.jspa?threadID=267944
    Thanks for your time.

    Hello,
    But i always see a static image for that gif.[http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#createCustomCursor(java.awt.Image,%20java.awt.Point,%20java.lang.String)]
    Note that multi-frame images are invalid and may cause this method to hang.--------
    Here is another approach:
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import javax.swing.*;
    class AnimatedCursorTest {
      private javax.swing.Timer animator;
      private JButton button;
      private Toolkit tk    = Toolkit.getDefaultToolkit();
      private Cursor[] list = new Cursor[3];
      private URL url00 = getClass().getResource("32x32_00.png");
      private URL url01 = getClass().getResource("32x32_01.png");
      private URL url02 = getClass().getResource("32x32_02.png");
      private Point p   = new Point(0,0);
      public JComponent makeUI() {
        list[0] = tk.createCustomCursor(tk.createImage(url00), p, "00");
        list[1] = tk.createCustomCursor(tk.createImage(url01), p, "01");
        list[2] = tk.createCustomCursor(tk.createImage(url02), p, "02");
        animator = new javax.swing.Timer(100, new ActionListener() {
          private int counter = 0;
          public void actionPerformed(ActionEvent e) {
            button.setCursor(list[counter]);
            counter = (counter<list.length-1)?counter+1:0;
        button = new JButton(new AbstractAction("Start") {
          public void actionPerformed(ActionEvent e) {
            JButton b = (JButton)e.getSource();
            if(animator.isRunning()) {
              b.setText("Start");
              animator.stop();
            }else{
              b.setText("Stop");
              animator.start();
        button.setCursor(list[0]);
        JPanel p = new JPanel(new BorderLayout());
        p.add(button);
        p.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        return p;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new AnimatedCursorTest().makeUI());
        frame.setSize(320,240);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

  • Animated Gif help

    I want to place an animated gif into an application. I want it to start of not animated then I click a button and it starts. I click another button and the animation stops? Where do I start?
    I have placed the gif into a JLabel and it starts animating.
    Thats all I know how to do
    Help!

    Ok, So far I have one image, animated gif. There are 2 copys of that with different names in my dir. Search1.gif and Search2.gif. I place search1 into a custome JPanel that just paints the image, no animation, second inmage in a JLabel, show animation. I start with the no animation image showing, ok, click a button and image dissappears, ok, add animation image, not ok. My custom image panel with gif is in a JPanel, the JLabel will also be added to the same JPanel
    searchPane.remove(image1);
    searchPane.repaint();
    searchPane.add(image2);
    ...code here...
    searchPane.remove(image2);
    searchPane.add(image1);

  • A mystery: Animated GIF not displaying correctly.

    I've started adding images to a >1 year old game that I kind of abandoned, which formerly used hard-coded graphics. I'm looking to use a 4 frame long animated GIF of what would appear to be a rotating blade-like enemy. (Not actually a blade, but this is irrelevant.)
    The GIF which I am using can be viewed here: ftp://72.141.73.226/ftproot/av.gif
    I have taken screenshots of the 4 frames I am receiving, and slowed the result down here: ftp://72.141.73.226/ftproot/broken.gif
    I'm not quite sure why it's doing that.. Any ideas?
    Also, I've got it programmed so that when the enemies are defeated, they emit a small explosion, which is also an animated GIF. It can be found here: ftp://72.141.73.226/ftproot/boom.gif
    The images are drawn by the class AI class, which extends JPanel (For the ImageObserver status). The image displayed is determined when a method called changeImg is called.
    public void changeImg (String img) {
        this.img = Toolkit.getDefaultToolkit().getImage(img);
    }When the health reaches 0, the 'boom' image (found above) is put onto the object's 'img' variable, which is later called like this:
    g.drawImage (img, x-w/2, y, x+w/2, y+h, 0, 0, 20, 20, this);Essentially, it draws the image at certain coordinates depending on the position of the user, and sizes the image depending on the size of the user (variable with difficulty.) and you can see where it is using 'this' as an ImageObserver, because it just so happens to be one. (This is the only way I know to display images.)
    There's a small problem, however. When the 'boom' graphic is loaded, it floats around in memory, not being drawn, because it's not being told to, but evidently goign through the animation anyway. This means that all explosions are synchronized, so say I defeat an enemy at frame 0, and then another one at frame 5. The 10 frame explosion is already half-complete, so the second enemy's explosion animation is the latter half of the explosion animation, followed by the inital half. I tried creating the GIF so that it would be set to 'play once', but then after the first enemy exploded, all enemies would display the last frame of the explosion, instead of playing the animation once.
    Any help would be greatly appreciated.
    (This isn't for homework, don't worry. I finished this assignment over a year ago, and just decided to add to it a bunch.)

    @OP:
    Are you aware of the fact that your FTP server is wide open?

  • Animated GIF - not working properly

    Hi,
    I'm trying to get an animated GIF working in my swing program. I am drawing on a JPanel using paintComponent.
    Here's the thing: It will animate, (faster then it should) and then pause animation for 5 seconds, then animate again. I am trying to achieve constant animation, at the framerate in which is set inside of the GIF file. Is there a better method to use then what I am using? It's not a repaint problem, as I am repainting constantly. Here's what I got:
    String filename = "myimage.gif";
    Image img = Toolkit.getDefaultToolkit().getImage(filename);
    g.drawImage(img, x + 28, y + 79, this);A code snippet would be helpful as I am only two weeks into Java and have difficultly reading the Sun documentation.
    Thanks for reading,
    Nate

    Does that entire code snippet appear in the paintComponent method? It should be more like this,
    String filename = "myimage.gif"
    Image img = Toolkit.getDefaultToolkit().getImage(filename);
    public void paintComponent(Graphics g) {
         g.drawImage(img,x+28,y+79,this);
    }You shouldn't try to get the image from the toolkit everytime. Just get it once, and everytime you paint the image, the next frame will be painted.
    To introduce a constant delay you can use javax.swing.Timer to simply repaint the panel whenever you want to. Here's sort of a basic example
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import java.awt.Image;
    public class GifAnimation extends JPanel
            implements java.awt.event.ActionListener {
        private Image img;
        private Timer timer;
        private int delay;
        public GifAnimation(String fileName) {
            java.awt.Toolkit toolkit = java.awt.Toolkit.getDefaultToolkit();
            //The image icon will load the image
            img = new ImageIcon(toolkit.getImage(fileName)).getImage();
            if (img.getWidth(null) == -1 && img.getHeight(null) == -1) {
                System.err.println("Unable to load image: " + fileName);
            }else {
                setPreferredSize(new java.awt.Dimension(img.getWidth(null),
                                                       img.getHeight(null)));
            //in milliseconds
            this.delay = 100;
        public int getDelay() {
            return delay;
        public void setDelay(int delay) {
            this.delay = delay;
            if (timer != null) {
                timer.setDelay(delay);
        //This method is called when a component is connected to a native
        //resource.  It is an indication that we can now start painting.
        public void addNotify() {
            super.addNotify();
            if (img.getWidth(null) != -1) {
                timer = new javax.swing.Timer(delay, this);
                timer.start();
        public void removeNotify() {
            super.removeNotify();
            if(timer != null) {
                timer.stop();
                timer = null;
        public void actionPerformed(java.awt.event.ActionEvent e) {
            //you can alternatively use paintImmediately(), but there are
            //going to be certain consequences to using that.
            repaint();
        public void paintComponent(java.awt.Graphics g) {
            //Clears the background before drawing the next frame
            super.paintComponent(g);
            if(img.getWidth(null) != -1) {
                int x = (getWidth() - img.getWidth(null))/2;
                int y = (getHeight() - img.getHeight(null))/2;
                g.drawImage(img,x,y,this);
    }In a GIF file each frame has a duration specified in hundreds of a second. And each frame also has an offset position (not all the frames need to have the same width or height). I can show you how to load this information from the file, but I'm not sure if it would bring major confusion. It requires the use of javax.imageio.ImageIO and javax.imageio.metadata.IIOMetadata . It also requires a recursive method to search the image's metadata for the needed information (a bit overwhelming for a person two weeks into java).

  • How do I add animated .gif files to a JFrame?

    Hi, I'm making an underwater scene in java for my degree assignment. I have a JFrame with an underwater background and a bunch of .gif fish moving around inside, but they should be animated and they're not. They animate outside of java. How can I make the .gif files animate?

    Hi, I'm making an underwater scene in java for my
    degree assignment. I have a JFrame with an underwater
    background and a bunch of .gif fish moving around
    inside, but they should be animated and they're not.
    They animate outside of java. How can I make the .gif
    files animate?A simple example:
    /* save as AnimeGif.java */
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    class AnimGifPanel extends JPanel{
      Image[] imgs;
      int w, h;
      Random rand;
      public AnimGifPanel(Image[] ims, int wid, int hei){
        imgs = ims;
        w = wid;
        h = hei;
        setPreferredSize(new Dimension(w, h));
        setBackground(Color.cyan);
        rand = new Random();
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        for (int i = 0; i < imgs.length; ++i){
          g.drawImage(imgs, rand.nextInt(w), rand.nextInt(h), this);
    public class AnimeGif{
    public static void main(String[] args){
    String filename = "fish.gif"; // an animated gif
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container con = frame.getContentPane();
    Image[] ia = new Image[5];
    for (int i = 0; i < ia.length; ++i){
    ImageIcon ic = new ImageIcon(filename);
    ia[i] = ic.getImage();
    AnimGifPanel agp = new AnimGifPanel(ia, 500, 400);
    con.add(agp, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);

  • Problem to display Animated Gif from HTML into JEditorPane

    I have a problem displaying animated gif that comes from URL (HTML) into JEditorPane.
    Let me show you the source I have:
    * @author Dobromir Gospodinov
    * @version 1.0
    * Date: Dec 6, 2002
    * Time: 6:47:53 PM
    package test.advertserver;
    import javax.swing.*;
    import java.awt.*;
    import java.io.IOException;
    public class Test {
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              JEditorPane ed = new JEditorPane();
              try {
                   ed.setPage("http://localhost:8200/servlet?key=value");
              } catch (IOException e) {
                   e.printStackTrace();
              JPanel panel = new JPanel();
              panel.setPreferredSize(new Dimension(500, 500));
              panel.add(ed);
              frame.getContentPane().add(panel);
              frame.pack();
              frame.setVisible(true);
    }Part of the returned from servlet HTML includes an img tag:
    <img src="/images/MyAnimatedGif.gif" alt="animated gif comment" width="480" height="50"  border="0">Let us assume that MyAnimatedGif.gif has 10 frames and gif is looped - when the 10th is dipslayed it has to display the 1st and so on.
    JEditorPane displays frames from 1 to 10 correctly but does not start from the first again. Instead JEditorPane displays a broken image.
    I locate where the problem arise:
    JEditorPane has an HTMLEditorKit that creates javax.swing.text.html.ImageView instance for every IMG tag.
    And here is the problem:
    ImageView has an ImageObserver necessary for the asynchronous image download. ImageObserver has the imageUpdate method. But this imageUpdate method is never called with ALLBITS flag raised up. Instead, after the last frame of MyAnimatedGif.gif is downloaded the imageUpdate method is called with flag ERROR raised up. Obviously this is a bug of Sun's implementation. Finaly the flag ALLBITS has to be received for normal end of image observing. But ALLBITS flag does not come.
    So, can anybody help me how to load an animated gif within JEditorPane completely.
    Thank You in advance,
    Dobromir Gospodinov
    P.S. If somebody of you wants to debbug what happens within ImageView will have to implement it (and related classes too, because of the limited package visability) borrowing the source from Sun's ImageView.

    I'm also having this problem with java 1.4.1 I discovered that some animated gifs work fine, while others stop animating. Running with java 1.3.1 fixed the problem. I'm going to report this as a bug
    Here's my code:
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    public class AnimatedGifTester
    extends JFrame
    public static void main(String argv[])
    throws Exception
    new AnimatedGifTester();
    public AnimatedGifTester()
    throws Exception
    String[] images = new String[] {
    "http://www.gif.com/ImageGallery/Animated/Animals/Photographic/dog_running.gif",
    "http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/java.gif",
    "http://www.webdeveloper.com/animations/bnifiles/anielg.gif",
    "http://www.webdeveloper.com/animations/bnifiles/cat2.gif",
    "http://images.animfactory.com/animations/animals/fish/big_fish_swimming_md_wht.gif",
    "http://www.webgenies.co.uk/images/martian.gif",
    "http://www.webdeveloper.com/animations/bnifiles/at_sign_rotating.gif",
    "http://www.webdeveloper.com/animations/bnifiles/arrow_1.gif",
    "http://www.gif.com/ImageGallery/Animated/Characters/Cartoon/javaacro.gif",
    "http://java.sun.com/products/java-media/2D/samples/suite/Image/duke.running.gif",
    "http://www.gif.com/ImageGallery/Animated/SouthPark/Cartoon/stan.gif"
    StringBuffer buffer = new StringBuffer("<html><body>");
    for (int idx = 0; idx < images.length; idx++)
    buffer.append("<img src='" + images[idx] + "'>");
    buffer.append("</body></html>");
    String html = buffer.toString();
    // save a copy of the html to open in a browser so we can see what it's
    // supposed to look like
    BufferedWriter writer = new BufferedWriter(new FileWriter("animatedGifTest.html"));
    writer.write(html);
    writer.close();
    JEditorPane editorPane = new JEditorPane("text/html", html);
    editorPane.setEditable(false);
    getContentPane().add(editorPane);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(new Dimension(400, 600));
    show();

  • Problem at displaying animated gif images !!!!!!!!!!!!

    hello everyone......i am trying to display an animated gif image..............so till far i have no issues on this....
    but i face problem when :
    i have created a class called SimpleGame which extends JPanel....
    public class SimpleGame extends JPanel
    //code
    public void paintComponent(Graphics g)
    //code to draw image
    }now i have written another class with main method
    public class MyGame extends SimpleGame
    public MyGame()
            JFrame frame=new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800, 600);
            frame.setUndecorated(true);
            frame.setLocationRelativeTo(null);
            frame.getContentPane().add(this);
            frame.setVisible(true);
            this.repaint();
    }so image gets displayed but only one frame of animated image......image that is displayed is static.....since it is a animated gif,,,,,so some how animation is not rendered......only one frame is displayed......
    why is it happening ??
    if i try to display animated image from a single class i mean my paintComponent method and main method is at same class then i do not face problem.....
    but if my paint method is in another class and i am using that method from another class then animation does not get rendered.........
    any help !!!!! please...........

    class SimpleGame extends JPanel
    Image img=new ImageIcon("y.gif");
    public void paintComponent(Graphics g)
    g.drawImage(img,150,150,this);
    }main class//
    class MyGame extends SimpleGame
    public MyGame()
            JFrame frame=new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800, 600);
            frame.setUndecorated(true);
            frame.setLocationRelativeTo(null);
            frame.getContentPane().add(this);
            frame.setVisible(true);
            this.repaint();
    public static void main(String[] args)
    new MyGame();
    }my image gets displayed.......but only single frame of a animated image....animation is not happening..........

  • Using an Animated GIF/JPEGs Effectively

    I have an animated GIF in an applet with around 200 frames, moving at a speed of 6 frames per second. However, when just drawing it in paint(), it looks extremely messy with the flashing. Then I tried another tack, and exported the gif as 200 jpeg files and used double buffering to draw it in a JPanel with the following code:
    public void load()
         images = new ImageIcon[numImages];
         for (int i=0; i<images.length; i++)
              String num = "" + i;
              if (num.length() == 1)
                   num = "00" + i;
              if (num.length() == 2)
                   num = "0" + i;
              images[i] = new ImageIcon(dir + imageNm + num + ".jpg");
         setSize(getPreferredSize());
         startAnim();
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         if (images[currentImage].getImageLoadStatus() == MediaTracker.COMPLETE)
              images[currentImage].paintIcon(this, g, 0, 0);
              currentImage = (currentImage + 1) % numImages;
    public void startAnim()
         if (animTimer == null)
              currentImage = 0;
              animTimer = new Timer(animDelay, this);
              animTimer.start();
         else if (!animTimer.isRunning())
              animTimer.restart();
    public void actionPerformed(ActionEvent e)
         if (currentImage == numImages-1)
              stopAnim();
         repaint();
    public void stopAnim()
         animTimer.stop();
    }However, the outOfMemory Exception appears after loading approximately the first 50 stills. Any suggestions, besides having to extend the memory usage?

    deltacoder, I tried what you suggested in the code below, to keep the images inside an array of 20 and to rotate them as soon as the image is displayed.
    public void init()
         images = new ImageIcon[20];
         for (int i=0; i<20; i++)
              String num = "" + i;
              if (num.length() == 1)
                   num = "00" + num;
              if (num.length() == 2)
                   num = "0" + num;
              images[i] = new ImageIcon(dir + imageNm + num + ".jpg");
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         if (images[currentImage%20].getImageLoadStatus() == MediaTracker.COMPLETE)
              images[currentImage%20].paintIcon(this, g, 0, 0);
              if (currentImage < (numImages-21))
                   String numStr = "" + (currentImage + 20);
                   if (numStr.length() == 1)
                        numStr = "00" + numStr;
                   if (numStr.length() == 2)
                        numStr = "0" + numStr;
                   images[currentImage%20] = new ImageIcon(dir + imageNm + numStr + ".jpg");
              currentImage++;
    }However, for some reason, it is still laggy. Can you perhaps see why from my code? must41, I am also working on your suggestion. In your thread for loading images, shouldn't there be some sleep time? Otherwise, the thread might get ahead of itself and cause outofmemory exception. And from what I know, whenever garbage collect runs, the code will run laggier than usual no matter what. Perhaps, I should have mentioned earlier, but there is also an AudioClip playing in the background (which does take up memory itself) that I like to match to the images (which i know will match because i made the animation using Flash MX), which is why I can't afford the lag from the garbage collecting.
    Perhaps there is a way to combine both of your suggestions?

  • Open and edit animated .gif while preserving frame timing

    CS4 Premium Design Edition, Win XP
    I was disappointed with the removal of Image Ready from CS3 because although some of the functionality was placed into Photoshop 10, there was no way to open and edit an existing animated .gif while preserving the timing of each individual frame. I was told on the PS forum at the time that I really needed to use Fireworks. I resented that, because I was very happy with Image Ready and I didn't want to have to learn a new application just to gain functionality that had been included in previous versions of PS/IM.
    I've now got CS4 Premium Design Edition which of course includs Fireworks... and here's what Help has to say on the subject of imported .gifs.
    "Note: When you import an animated GIF, the state delay setting defaults to 0.07 seconds. If necessary, use the States panel to restore the original timing."
    This is no use to me. What if I don't know the individual frame timings? What if there are 200 frames with varying timings?
    Simple question: which current Adobe product is capable of importing a .gif while retaining the frame timings? If anyone knows, or if I've misunderstood the nature of the Fireworks Help quote above, I'd really appreciate some input here. Thanks :)
    Not so simple question: why was an excellent gif-editing application thrown out to have its functionality partially replaced by a bunch of scripts and half-effective workarounds cooked up by desperate users ("import a gif by using the video import and typing *.* into the filename box..")? It's a fair question I think.
    Mark

    Hi Bob, that's not glib at all, it's a reasonable question.
    I uninstalled it along with everything else when I installed CS3, in the reasonable expectation that whatever replaced IR would be at least equal in functionality.
    Perhaps I should just dig out CS2 and install IM from there, but I have some serious reservations about doing so, because I don't know if/how a partial install of CS2 will impact upon my installation of CS4, and I'm not confident of getting support.
    I am also curious to know if/why Adobe actually removed basic functionality without replicating or replacing it in their other software. I really want to know: which recent, currently supported Adobe product
    should I be using in order to regain this functionality? Or do Adobe no longer produce a geniuinely comprehensive .gif-editing application?
    Mark

Maybe you are looking for

  • Jstl c:if test

    I have put a string in my request: pageContext.getRequest().setAttribute("photoAccountmanager", "SUCCESS"); How can I retrieve the string in jstl? The next statement doesn't work: <c:if test="${request.photoAccountmanager == 'SUCCESS'}" > </c:if>

  • Change default key size on non Domain joined CA.

    Hello, I have one standalone non domain joined CA I would like to change the default key size of all issued certs to 2048.  Since it is a stand along, there are no AD template to modify.  Can this be changed in the registry? Shawn

  • How to pass data from one page to another

    i have a table with multiselect and i want that in the moment i select some rows and press on a button in the other page should be displayed only those data i have selected from previous one.... how can i do this? any link or example for this case? t

  • First time scripting question

    Is this a situation where I should learn how to use scripting in DVD Studio? I have a video with 12 chapters with chapter markers. When a viewer chooses to watch an individual chapter, rather than the full video, I want a 10 second video to play befo

  • Hi experts SEM-BPS

    Hi Guys, i am new to BPs ,can any one send me the documents regarding all planning functions with examples. Thanks in advance manoj