Animated GIF image gets distorted while playing.

I have some animated gif images which I need to show in a jLabel and a jTextPane. But some of these images are getting distorted while playing in the two components, though these images are playing properly in Internet Explorer. I am using the methods insertIcon() of jTextPane and setIcon() of jLabel to add or set the gif images in the two components. Can you please suggest any suitable idea of how I can get rid of this distortion? Thanks in advance.

In the code below is a self contained JComponent that paints a series of BufferedImages as an animation. You can pause the animation, and you specify the delay. It also has two static methods for loading all the frames from a File or a URL.
Feel free to add functionality to it, like the ability to display text or manipulate the animation. You may wan't the class to extend JLabel instead of JComponent. Just explore around with the painting. If you have any questions, then feel free to post.
The downside to working with an array of BufferedImages, though, is that they consume more memory then a single Toolkit gif image.
import javax.swing.JComponent;
import java.awt.image.BufferedImage;
import java.awt.Graphics;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
public class JAnimationLabel extends JComponent {
    /**The default animation delay.  100 milliseconds*/
    public static final int DEFAULT_DELAY = 100;
    private BufferedImage[] images;
    private int currentIndex;
    private int delay;
    private boolean paused;
    private boolean exited;
    private final Object lock = new Object();
    //the maximum image width and height in the image array
    private int maxWidth;
    private int maxHeight;
    public JAnimationLabel(BufferedImage[] animation) {
        if(animation == null)
            throw new NullPointerException("null animation!");
        for(BufferedImage frame : animation)
            if(frame == null)
                throw new NullPointerException("null frame in animation!");
        images = animation;
        delay = DEFAULT_DELAY;
        paused = false;
        for(BufferedImage frame : animation) {
            maxWidth = Math.max(maxWidth,frame.getWidth());
            maxHeight = Math.max(maxHeight,frame.getHeight());
        setPreferredSize(new java.awt.Dimension(maxWidth,maxHeight));
    //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() {
        //Make anonymous thread run animation loop.  Alternative
        //would be to make the AnimationLabel class extend Runnable,
        //but this would allow innapropriate use.
        exited = false;
        Thread runner = new Thread(new Runnable() {
            public void run() {
    public void removeNotify() {
        exited = true;
    /**Returns the animation delay in milliseconds.*/
    public int getDelay() {return delay;}
    /**Sets the animation delay between two
     * consecutive frames in milliseconds.*/
    public void setDelay(int delay) {this.delay = delay;}
    /**Returns whether the animation is currently paused.*/
    public boolean isPaused() {
        return exited?true:paused;}
    /**Makes the animation paused or resumes the painting.*/
    public void setPaused(boolean paused) {
        synchronized(lock) {
            this.paused = paused;
    private void runAnimation() {
        while(!exited) {
            if(delay > 0) {
                catch(InterruptedException e) {
                    System.err.println("Animation Sleep interupted");
            synchronized(lock) {
                while(paused) {
                    catch(InterruptedException e) {}
    public void paintComponent(Graphics g) {
        if(g == null) return;
        java.awt.Rectangle bounds = g.getClipBounds();
        //center image on label
        int x = (getWidth()-maxWidth)/2;
        int y = (getHeight()-maxHeight)/2;
        g.drawImage(images[currentIndex], x, y,this);
        if(bounds.x == 0 && bounds.y == 0 &&
           bounds.width == getWidth() && bounds.height == getHeight()) {
             //increment frame for the next time around if the bounds on
             //the graphics object represents a full repaint
             currentIndex = (currentIndex+1)%images.length;
        }else {
            //if partial repaint then we do not need to
            //increment to the the next frame

Similar Messages

  • Problem with animated gif image getting displayed

    My problem is that my animated image does not get displayed properly. I am extending JButton and the button already contains a static image. I want to display the animated image over the static one for some reason. If I replace the animated image with a static gif, then there is no problem.
    Here is the code that I am using
    Icon anim = new ImageIcon((new ImageLoader()).getImage("/graphics/busy.gif"));
    // thread to call displayAnim method
    class ColorThread extends Thread {
    ColorThread() {
    public void run() {
    while (AnimFlag) {
    try {
    } catch (InterruptedException e) {
    public void displayAnim()
    public void paint(Graphics g)
    int x=5;
    int y=0;
    if ( AnimFlag) {

    This code is working fine for JRE 1.2 and the animation is displayed. The problem is with JRE 1.3. when there is no animation, neither is there any image getting displayed.

  • Animated gif changes color palette while playing

    Hi everyone,
    I've been creating animted gifs using Matlab and the ImageMagick suite (convert). If I open the gifs in Preview, the color comes out fine in each frame; however i I use Quicktime (which is necessary, that's what we use for presentations) the color palette will change as the frames play.
    I just got the newest version of Quicktime, hoping that it would solve the problem, but it didn't. Any ideas?

    I'm not familiar to the software but I can guess what is happening.
    Too many colors. A GIF is 8 bit (256 colors) but some of them are not used by all software. Windows and Mac's are different.
    Does the software offer a way to reduce the number of colors used? Can you get it down to 8 bit? Can you discard unused colors with some other software?
    Have you considered building an image sequence movie? These allow many different images formats and support up to 32 bit formats (millions of colors).
    QuickTime Pro ($30) can import a series of images as a movie. The file size is much smaller than any video format used today (just the total of the images file size).

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

    hello everyone......i am trying to display an animated gif 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
    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.setSize(800, 600);
    }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)
    }main class//
    class MyGame extends SimpleGame
    public MyGame()
            JFrame frame=new JFrame();
            frame.setSize(800, 600);
    public static void main(String[] args)
    new MyGame();
    }my image gets displayed.......but only single frame of a animated image....animation is not happening..........

  • Where can I find video training to make animated GIF images?

    I would like to get more info on how to make animated GIF images with my Photoshop for my WordPress blog here

    Hello Bill,
    you could have a look at >>> ... till save the animation
    and at the end: Adobe also recommends >>> at
    If the German language is no problem for you, you could use

  • Animated Gif Image does not render correctly on screen

    I have added animated gif image to the scene it does not render shakes on the screen. plz give me any suggestion
    i use following code
    Image logo= new Image(getClass().getResourceAsStream("images/image.gif"));
    logoLabel.setGraphic(new ImageView(logo));

    Hello user,
    I think gif are rendered smoothly.
    Are you sure you are not making many object of same images everytime?

  • Animated gif image

    I like to create an animated gif image from a given set of images with java. I like to do this with the given set of java api as I do not want to use a commercial graphics library. Can anyone provide me with a sample example.

    I like to resize a gif image. Currently i am using the following code but the resized image is not smooth.
    public BufferedImage resizeImage(BufferedImage img, int newW, int newH)
              int w = img.getWidth();
              int h = img.getHeight();
              BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
              Graphics2D g = dimg.createGraphics();
              g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
              g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
              return dimg;
    Is there a way to resize a gif image in a smooth way as the example given in the gif4j library

  • Animated GIF Image on a JPanel.

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

    I think this code should display an animated GIF image on a JPanel.
    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) {
    // 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");
    jPanel.add(imageLabel, BorderLayout.CENTER);
    frame.getContentPane().add(jPanel, java.awt.BorderLayout.CENTER);

  • In Edit mode the image gets distorted as if a graphics card error...

    When I enter edit mode, many times the image gets distorted and is unrecognizable. The image is covered in red or green lines like when a driver or graphic card is having problems. I can view the image if I use the shift key or exit edit mode.
    Have the latest version of both OS and iPhoto. Am considering a complete reinstall of the OS and Software but would like to avoid if possible.

    Welcome to the Apple Discussions.
    Well you can avoid the hassle of re-installing because it won't help. This is a bug that affects some users of 10.6 and iPhoto, Aperture and/or Preview. Currently there is no solution.
    iPhoto menu -> Provide iPhoto Feedback
    and let them know that you too have the issue.

  • When using the smart brush tool, my image gets distorted.  Is there anyway to fix this?

    When using the smart brush tool, my image gets distorted.  Is there anyway to fix this?

    What preset have you selected?
    Can you post a screenshot showing the distortion.
    Insanity is hereditary, you get it from your children
    If this post or another user's post resolves the original issue, please mark the posts as correct and/or helpful accordingly. This helps other users with similar trouble get answers to their questions quicker. Thanks.

  • Hi, I have downloaded some avi files and mov files. i am not getting audio while playing the movie. i tried to play with iTunes, QT, DivX player. but I am getting audio in mp4 files. can u help me to fix this

    Hi, I have downloaded some avi files and mov files. i am not getting audio while playing the movie. i tried to play with iTunes, QT, DivX player. but I am getting audio in mp4 files. can u help me to fix this

    First, back up all data and then uninstall "DivX" according to the developer's instructions.
    Then try this:
    VideoLAN - Download official VLC media player for Mac OS X

  • Firefox gets Stuck while Playing Facebook Games and Working in Another Tab

    Firefox gets stuck while playing facebook games (restaurant city) and side by side working in another tab or window of firefox. Switching between tabs takes time and on facebook scrolling doesn't remain smooth it gets stuck again and again while scrolling the page.
    Also, in earlier versions it was a great feature that when once a game is loaded then when i open it second time it was loaded immediately without any complete loading but now every time you play the same game it will load completely which happens generally when we reinstall firefox so that our saved cookies gets destroyed.
    == This happened ==
    Every time Firefox opened
    == The 3.6 versions came up

    same things happen to me also the cache system is so slow it even download the flash player game after 3 or 4 days completely and hang is always the error when ever i use the fire fox also there is one more thing some time computer is not opening any site what ever u type mozilla is disconnected from IP what ever he issue is but if u close the firefox and start again it is working for a while after some time it may happen again time is not counted over this matter so i m sure this is the trouble from fire fox coz other browsers are working in the same time while mozila sucks

  • My iphone 6 is getting stucked while playing music and the voice getting down in between

    My iphone 6 is getting stucked while playing music and the voice getting down in between

    Hi Nision,
    The webpage linked below provides details on how to set up service for your iPhone.
    Service Answer Center - iPhone

  • How combine a jpeg image & animated gif image & save  it as GIF ?

    i have an jpeg image, & also aminated gif image, how do i place the animated gif image over (in the center of the image) a jpeg image & save it as gif file ??

    First thing you need to do is stop thinking in terms of file formats once the files are in photoshop they are all the same. The exception being vector vs raster. But in this instance the process is rteally the same so 6 on one hand a half a dozen on the other. Or as some would say Tomatoe, tomahtoe(mispelled on purpose).
    The jpeg I would assume is the background image and the gif image is the fore ground object. Open the jpeg, and then place the gif file. As long as the fore ground object has transparency, your job is pretty much done. If not, then it will be up to you to mask what you want to keep vs what you don't and apply that selection to the foregrounds layer as a mask.
    Google the net or skim the users manual for the keywords - mask, selections, quickmask, pen tool, paths. Each of these can in one way or another take care of your issue.
    It would be worth your time to also go through the numerous videos about photoshop and see how its done.
    Either go to adobe tv,
    Itunes podcasts
    or one of the following web sites:

  • I finished making an animated .gif image in FireWorks. My question is, how do I convert it into video so that when I edit video, that every video editing program recognizes it? Long story short, How do I convert animated .gif files into video formats?

    I worked in Adobe FireWorks to make the animated .gif. What program do I use to convert the file from .gif to any video format: .mp4, .m4v, .avi, .wmv, etc. I want to convert it into video format, so that QuickTime Player plays the video, I can insert it into iMovie '11 and edit, and also insert it into Final Cut Pro X and edit video.

    Thanks for getting back with me so promptly.  It has taken me this time to connect with the proper people to find out the information you requested.
    The camera used to film the class was a Panasonic AG-HMC40P, owned by a local cable TV station; they use Kodak video encoding software, and a SD card was used to store the video.   The file extension is .mts, and the mime file is MPEG 2 transport.  He said I probably need an AVCHD converter, and the Mac app store lists 8 of those options, 4 free and 4 for up to $9.99.  He said I'll also need a converter for later plans of posting on YouTube or on the website, and while some of those in the app store might work for the later needs, he knows one app called "Compressor" that would work for the uploading later.  He also suggested I could try renaming the .mts file to .MP2T, but he wasn't sure that would work.
    They don't work with Macs at the studio, but I had thought I could have some lessons there in editing, and apply what I learned to my iMac and iMovie.
    First, though, I have to be able to see it and review it!
    Thanks again!

Maybe you are looking for

  • Transferring iTunes library to main user account

    I have recently upgraded to a mac after using a PC for many years. I set up my MAC with a user account and then once we upgraded to Lion, used migration assistant to copy all the PC files across - it copied them into a new user account on my MAC (whi

  • How to increase the width of a report

    Respecetd guru's, i am facing problem to generate a report in our oracle report biulder. becuase i have task to generate FORM NO.X .though i am in HRM module is has so many entity inside .and when i am trying to put thsese its exceed the margn line.

  • Inline (non full-screen) video in stageWebView for iPhone (iOS)???

    According to this post (below), all we need in order to allow native inline video for the iPhone is a simple Obj-C property webview.allowsInlineMediaPlayback = YES; in conjunction with adding "allowsInlineMediaPlayback" to the html5 video tag. http:/

  • Contribute won't let me publish

    I have Contribute CS4 and a Mac 10.5.8. When I open my webpage to edit, it says 'another instance' is working on the draft. When I plow ahead and make the edit changes anyway, it works fine but won't allow me to publish. When I hit publish it won't a

  • An ActionScript error has occured - Flash Player

    Hello, I keep getting this kind of errors whenever I visit a website that has adobe flash on it and it is very very annoying guys, please do something about it. It doesn't happen on all websites but but quite frequently I'm using the latest Firefox b