Animated Gif Repaint

I knew I was going to end up here eventually, stupid animated gifs.
First of all, I get weird drawing artifacts on an animated gif on jkd 1.5, I upped this to 1.6 and everything is cool with displaying the gif. It could be because I'm running JBuilder in a XP VM. I don't really care how to fix this, or if its even fixable, I'm just pointing it out.
I have an animated gif in an imageicon. The program is hangman, and the gif shows a stick figure walking up onto the podium to get hung. I would like to play the gif once, every time the "New Game" button is clicked. I have tried a variety of things to do so, including JLabel1.repaint(); calling the label again, etc, etc. I'll try to post the relevant bits of my code.
public class HangFrame
    extends JFrame implements ActionListener {
  public HangFrame()
    try {
      jbInit();
    catch (Exception ex) {
      ex.printStackTrace();
  }jbinit calls the placement of all the items.
    jLabel1.setBounds(new Rectangle(19, 57, 550, 400));
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == start) {
      start();
....'start' is my name for the button that reads "New Game".
The start method contains:
ImageIcon maingif = new ImageIcon( (ClassLoader.getSystemResource(
        "hang1.gif")));
     jLabel1.setIcon(maingif);
//I've been trying different stuff right here, like repaint.The image displays correctly, and runs once (per the setting I gave it in flash, or thats how java does it).
I've searched extensively (seems I got lucky by just managing to get it to display once :D). I saw that I might have to flush the image or something like that, but I'm not really sure what that means. I've never had any experience with the graphics and paint component, most of the work we do in class is console and algorithm stuff. I got bored over break and made my hangman into a swing app. I'd appreciate any help.
Oh, and sorry if this should be in the swing subforum, I figured my issue was too basic for it.
Edited by: rpk5000 on Dec 31, 2007 8:52 AM

rpk5000 wrote:
This is where you're wrong. Dipshits like you post **** like this all the time when it's readily available information that can be searched for WITHOUT >hosing up our forums.Great, give me a link, or even a search term to use on google or these forums. Before you give me search terms, you might want to actually check and make sure the answer is somewhere there...are you out of your freakin mind?!?!?!
go to google and type "java gif animation"
you think you're the first person to want to do this?!?!
moreover, search the forums here
you think you're the first person to ask for this here?!?!
You would think "repainting an imageicon animated gif java" would give a page that has the answer on it within the first 10 results but....
I'm looking for a page that simply says, take your imageicon and call.... (repaint();) or whatever to make it run one more time.Did you even read the API for ImageIcon! It took me 2 seconds to find the information for animating gifs as imageicons.
Well Java just sucks now doesn't it. Stop using animated gifs and Java since they suck. There, problem solved!I like Java a lot, I'm just saying, in certain instances it seems to fall short.No, YOU fall short. I found the solution in 3 seconds.
This is a "New to Java" subforum, if you can't handle helping people in a pleasant manner, that shows you respect the other person, what do you think people will think of you and java. If I spent more time on forums like this, and was looking at which language to try, I doubt I would pick java.I don't care what you think of me OR Java. I'm tired of noobs wasting forum resources with this crap. Once I was new to everything, but I went to the library and when the internet came along i learned how to search it!
Critical thinking people. Don't we teach this in schools any more?!
When it becomes an Internet joke (http://thedailywtf.com/Articles/plz-email-me-teh-codez.aspx) about how bad the sun forums are, well, you really need to reconsider what you want to do with your life.
LMAO! You are the daily WTF!
Edited by: wpafbuser1 on Dec 31, 2007 1:52 PM

Similar Messages

  • Animated GIF in JTabbedPane - repaint madness!

    Loading and animated GIF into the icon for a JTabbedPAne just works, but it causes the paintComponent method on the main part of the panel to be called repeatedly. Anyway to distinguish between the two areas? The icon repaints automatically but I don't want to have to repaint the rest of the panel unnecessarily.

    I've run into the same problem simon, the only way I came over this was to do my own animation for the gif. Bit of a bother really. Anyone have any other solutions?

  • Disabled JMenuItem doesn show animated gif

    Hi there
    I would like to have a popup menu with actions that are enabled after they have finished with some background task taking some time. Basically this works fine for the enabling action on a shown popup. However, adding an animated gif as the icon or disabled icon does not show it in disabled state. In enabled state it works perfect. Please have a try with the sample code. You should see the disabled item for 2 secs and the icon is not showing up. After being enabled, it does. Invoking the menu again shows the animated gif in its last state left, but not moving any more.
    I guess, repaints are not done appropriately in disabled state... Any ideas how to solve that would be highly appreciated :-)
    Actually I used the icon at http://mentalized.net/activity-indicators/indicators/pascal_germroth/indicator.white.gif
    Cheers
    Daniel
    public class Main
      public static void main(String[] args)
        final JFrame frame = new JFrame();
        frame.addMouseListener(new MouseAdapter()
          public void mousePressed(final MouseEvent e)
            final JPopupMenu popup = new JPopupMenu();
            popup.add(new JMenuItem("Open..."));
            popup.add(new JMenuItem("Close"));
            final JMenuItem action = new JMenuItem("Long loading until enabled");
            action.setIcon(new ImageIcon("C:/spinner.gif"));
            action.setDisabledIcon(new ImageIcon("C:/spinner.gif"));
            popup.add(action).setEnabled(false);
            popup.show(e.getComponent(), e.getX(), e.getY());
            SwingUtilities.invokeLater(new Runnable()
              public void run()
                try
                  Thread.sleep(2000);
                  action.setEnabled(true);
                catch (InterruptedException e1)
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }Edited by: daniel.frey on Apr 22, 2009 7:50 AM

    The problem is that you are causing the EDT to sleep, which means the GUI can't repaint itself. Read the section from the Swing tutorial on Concurrency to understand what is happening.

  • Animated GIF problems

    I've recently implemented an extension of IconView to animate gifs correctly in editor panes. I am just haveing two problems with it that I can't figure out.
    Firstly, when an animated gif is added it animates fine. The next time the same gif is added, it doesn't animate, just shows the last image of the animation. I assume that something is trying to be clever by caching the image somewhere, is there any way around this?
    Secondly some of the gifs do not animate very well. I believe that they may be using transparency to leave the contents of previous frames behind, but I guess that java does not support this. Any thoughts on how I could solve this?
    Here is the simple code for my view:
    class AnimatedIconView extends IconView implements ImageObserver
         private Container container = null;
         private Rectangle bounds = null;
         public AnimatedIconView(Element e)
              super(e);
              Icon icon = StyleConstants.getIcon(getAttributes());
              if (icon instanceof ImageIcon)
                   ((ImageIcon)icon).setImageObserver(this);
         public void setParent(View parent)
              super.setParent(parent);
              container=getContainer();
         public void paint(Graphics g, Shape s)
              super.paint(g,s);
              bounds=s.getBounds();
         public boolean imageUpdate(Image img,int infoflags,int x,int y,int width,int height)
              if (((infoflags & ImageObserver.FRAMEBITS)>0)&&(container!=null)&&(bounds!=null))
                   container.repaint((int)bounds.getX(),(int)bounds.getY(),(int)bounds.getWidth(),(int)bounds.getHeight());
              return true;
    }Dave

    I just can point you the bug which is probably related to your problem:
    http://developer.java.sun.com/developer/bugParade/bugs/4725530.html

  • Animated gif in a JButton which is a CellRenderer...

    I'm currently dealing with quite a huge thing...
    My cellRenderer is here to give a button aspect, this button has 3 kind of icons in fact :
    a cross when the line is ready to be treated
    a loading animation while in treatment... and here is the problem
    a tick whe the line has been treated
    i see the loader (but not always...) and not animated at all ...
    I change the states of the button in aother class, which has its own thread....
    .. as for no as see the lines being ticked line by line, cool, but if the loader could move between the 2 step, it would be perfect..
    Here is my class :
    * Create a special cell render for the first column of the images table
    * This cell render let us display a JButton associated with the given file in order
    * to permit its deletion from the tablelist
    * @author Gregory Durelle
    public class DeleteCellRender extends JButton implements TableCellRenderer , Runnable{
         private static final long serialVersionUID = 1L;
         int row;
         JTable table;
         public DeleteCellRender(){
             this.setIcon(Smash.getIcon("cross.png"));
              this.setBorderPainted(false);
              this.setForeground(Color.WHITE);
              this.setOpaque(false);
              this.setFocusable(false);
         public Component getTableCellRendererComponent( JTable table, Object value,boolean selected, boolean focused, int row, int column) {
              this.setBackground(table.getBackground());
              if(((DataModel)table.getModel()).getImageFile(row).isSent()){
                   this.setIcon(Smash.getIcon("tick.png"));//Smash is my main class & getIcon a static method to retrieve icons throug getRessource(url) stuff
                   this.setToolTipText(null);
              else if(((DataModel)table.getModel()).getImageFile(row).isSending()){
                   this.setIcon(Smash.getIcon("loader.gif")); //HERE IS THE PROBLEM, IT SHOULD BE ANIMATED :(
                   this.setToolTipText(null);
                   this.row=row;
                   this.table=table;
                 Thread t = new Thread(this);
                 t.start();
              else{
                   this.setIcon(Smash.getIcon("cross.png"));
                   this.setToolTipText("Delete this image from the list");
              return this;
         public void run() {
              while(true){
                   repaint();//SEEMS TO DO NO DIFFERENCE...
    }I tried to add a no-ending repaint but it does not make any difference... so if the Runnable annoy you, consider it deosn't exist ;)
    Someone has any idea of how to make an animated gif in a JButton which is in fact a CellRenderer ??....
    .. or maybe a better idea to make the loader appearing at the place of the cross, before the appearition of the tick....
    Edited by: GreGeek on 11 juil. 2008 23:04

    whooo :( you mean making a customized button ?
    like : public class MyButton extends AbstractButton{
       public void paintComponents(Graphics g){
          ...//img1 - wait 15ms - img2 - wait15ms - img3 - etc
    }that would be a solution, but i was pretty sure it would be possible to do more simple, and that i only forgot a very small thing to make it work...

  • Animated GIF image gets distorted while playing.

    Hi,
    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;
    import javax.imageio.stream.ImageInputStream;
    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() {
            super.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() {
                    runAnimation();
            runner.setDaemon(true);
            runner.start();
        public void removeNotify() {
            exited = true;
            super.removeNotify();
        /**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;
                lock.notify();
        private void runAnimation() {
            while(!exited) {
                repaint();
                if(delay > 0) {
                    try{Thread.sleep(delay);}
                    catch(InterruptedException e) {
                        System.err.println("Animation Sleep interupted");
                synchronized(lock) {
                    while(paused) {
                        try{lock.wait();}
                        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
    }

  • Animated .gif in JTable cell

    Hi -
    I have an actual animated .gif that I would like to display in a JTable's cell. By 'actual animated .gif', I mean that it is one file that is animated, and not a succession of files that I would loop through to look like animation.
    I have edited the following code that I found in a previous post. My .gif does display in the JTable and animates only ONCE. Once it animates once, it stops. How can I cause it to keep looping through and repeating the animation?
    Thanks!
    Kelly
    Code below:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class AnimatedIconTableExample extends JFrame
    public AnimatedIconTableExample()
    super("AnimatedIconTable Example");
    final Object[][] data = new Object[][]
    { new ImageIcon("images/Upload.gif") }
    final Object[] column = new Object[]
    { "Image Uploading" };
    AbstractTableModel model = new AbstractTableModel()
    public int getColumnCount()
    return column.length;
    public int getRowCount()
    return data.length;
    public String getColumnName(int col)
    return (String) column[col];
    public Object getValueAt(int row, int col)
    return data[row][col];
    public Class getColumnClass(int col)
    return ImageIcon.class;
    JTable table = new JTable(model);
    table.setRowHeight(50);
    setImageObserver(table);
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
    private void setImageObserver(JTable table)
    TableModel model = table.getModel();
    int colCount = model.getColumnCount();
    int rowCount = model.getRowCount();
    for (int col = 0; col < colCount; col++)
    if (ImageIcon.class == model.getColumnClass(col))
    for (int row = 0; row < rowCount; row++)
    ImageIcon icon = (ImageIcon) model.getValueAt(row, col);
    if (icon != null)
    icon.setImageObserver(new CellImageObserver(table, row,
    col));
    class CellImageObserver implements ImageObserver
    JTable table;
    int row;
    int col;
    CellImageObserver(JTable table, int row, int col)
    this.table = table;
    this.row = row;
    this.col = col;
    public boolean imageUpdate(Image img, int flags, int x, int y, int w,
    int h)
    if ((flags & (FRAMEBITS | ALLBITS)) != 0)
    Rectangle rect = table.getCellRect(row, col, false);
    table.repaint(rect);
    return (flags & (ALLBITS | ABORT)) == 0;
    public static void main(String[] args)
    AnimatedIconTableExample frame = new AnimatedIconTableExample();
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    frame.setSize(300, 150);
    frame.setVisible(true);

    I've heard of that problem before... I think it has something to do with how the image is loaded. I found an example of how Sun does animated gifs here: http://java.sun.com/products/java-media/2D/samples/suite/Image/DukeAnim.java
    I hope it helps.

  • 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);

  • 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).

  • 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?

  • Animated GIF in a StyledEditorKit?

    Im trying to figure out how to add support for animated gifs to the StyledEditorKit. This must be possible somehow since the HTMLEditorKit supports animated gifs.
    My problem is that I can't quite figure out where to start. I have tried just creating an ImageObserver that tells the component to repaint every time a new frame is loaded, but that didn't seem to do anything.
    I think I have to create a new View and create my own ViewFactory to generate it, but how can I let the component know that it has to redraw a particular view?
    Dave

    whooo :( you mean making a customized button ?
    like : public class MyButton extends AbstractButton{
       public void paintComponents(Graphics g){
          ...//img1 - wait 15ms - img2 - wait15ms - img3 - etc
    }that would be a solution, but i was pretty sure it would be possible to do more simple, and that i only forgot a very small thing to make it work...

  • Refreshing animated gif in Jlabel

    Hi,
    I've created a GUI for a cashmachine application and have the problem that my animated GIF's work on the first call, but only display the last frame of the animation on subsequent calls.
    I've tried alot of things, including validate, repaint, refresh but im running out of ideas!
    I have come to this assumption because I have created a copy of the animation and imported that on the second call and it works like it should. However once again on subsequent calls it simply displays the last from and doesn't animate.
    The code looks like this:
    public JLabel getInsertCardGraphic() {
              /* Imports the enter card gif */
              ImageIcon enterCardGraphic= new ImageIcon(LOCATION+"moving-card2.gif");
              JLabel enterCardHolder = new JLabel(enterCardGraphic);
              return enterCardHolder;
         }which is called from:
    public void actionPerformed(ActionEvent evt) {
              playBeep();          //not related to problem     
              eastPane.removeAll();
              eastPane.add(getInsertCardGraphic(), BorderLayout.CENTER); //called here
              eastPane.add(getCashSlotImage(), BorderLayout.SOUTH);
              eastPane.validate();
              String cardNum = cardlist.getSelectedItem().toString(); //unrelated code
              char[] pinArray = new char[4];
              pinArray[0] = cardNum.charAt(12);
                    pinArray[1] = cardNum.charAt(8);
                    pinArray[2] = cardNum.charAt(4);
                    pinArray[3] = cardNum.charAt(0);
              String encryptedPIN = new String(pinArray);
              // Tell controller that a card has been entered.
              Controller.getInstance("Ipl/ATM/Model/Model").cardEntered( cardlist.getSelectedItem().toString(), encryptedPIN);
         }if anyone has any suggestions on what I should do I will be extremely greatful!!
    Cheers,
    Hakan
    Edited by: hakz on Nov 13, 2007 5:01 AM

    Animated gif is working fine for me.
    You can check the delay time between the images in the gif, to see that it's not too short.
    Here's a simple example:import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.ImageInputStream;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import com.sun.imageio.plugins.gif.GIFImageMetadata;
    import com.sun.imageio.plugins.gif.GIFImageReader;
    public class AnimatedGifTest {
        public static void main(String[] args) {
            try {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                URL url = new URL("http://www.gifanimations.com/action/SaveImage?path=/Image/Animations/Cartoons/~TS1176984655857/Bart_Simpson_2.gif");
                frame.add(new JLabel(new ImageIcon(url)));
                frame.pack();
                frame.setVisible(true);
                // Read the delay time for the first frame in the animated gif
                GIFImageReader reader = (GIFImageReader) ImageIO.getImageReadersByFormatName("GIF").next();
                ImageInputStream iis = ImageIO.createImageInputStream(url.openStream());
                reader.setInput(iis);
                GIFImageMetadata md = (GIFImageMetadata) reader.getImageMetadata(0);           
                System.out.println("Time Delay = " + md.delayTime);
                reader.dispose();
                iis.close();
            } catch (Exception e) {e.printStackTrace();}
    }

  • JFileChooser animated gif preview

    I'm using an Accesory with an ImageIcon to preview images on a JFileChooser.
    It works ok, but I would like to know how do I get those animated gif to restart their animation whenever I click some other file (so the image preview goes to null) and click back on them.
    There are non-looped gifs and looped ones, it is specially for the non-looped gifs as to give a way to get to see the animation again. After clicking the file once the animation never plays again, even if a load another preview by clicking another file and then go back...
    Since there's no obvious method on ImageIcon or Image I tried flush since it says it clears the data but the only thing I got was the gif animating improperly (it would get trash/noise).
    * JFileChooserImagePreview.java
    * Created on 16 de junio de 2005, 12:58 AM
    package ptcg.win.util;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import java.io.File;
    /* from FileChooserDemo2.java. */
    public class JFileChooserImagePreview extends javax.swing.JComponent implements PropertyChangeListener {
         public JFileChooserImagePreview(JFileChooser fc) {
              setHeight = -1;
              setWidth = -1;
              setPreferredSize(new Dimension(100, 50));
              fc.addPropertyChangeListener(this);
         public JFileChooserImagePreview(JFileChooser fc, int setHeight, int setWidth) {
              this.setHeight = setHeight;
              this.setWidth = setWidth;
              setPreferredSize(new Dimension(setHeight, setWidth));
              fc.addPropertyChangeListener(this);
         public void propertyChange(PropertyChangeEvent e) {
              boolean update = false;
              String prop = e.getPropertyName();
              //If the directory changed, don't show an image.
              if(JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
                   file = null;
                   update = true;
              } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
                   file = (File) e.getNewValue();
                   update = true;
              //Update the preview accordingly.
              if (update) {
                   thumbnail = null;
                   if(isShowing()) {
                        loadImage();
                        repaint();
         public void loadImage() {
              if (file == null) {
                   thumbnail = null;
                   return;
              ImageIcon tmpIcon = new ImageIcon(file.getPath());
              if (tmpIcon != null) {
                   Image i = tmpIcon.getImage();
                   //i.flush(); //screws the animation
                   thumbnail = new ImageIcon(i.getScaledInstance(setHeight, setWidth, Image.SCALE_SMOOTH));
         protected void paintComponent(Graphics g) {
              if (thumbnail == null) {
                   loadImage();
              if (thumbnail != null) {
                   int x = getWidth()/2 - thumbnail.getIconWidth()/2;
                   int y = getHeight()/2 - thumbnail.getIconHeight()/2;
                   if (y < 0) {
                        y = 0;
                   if (x < 5) {
                        x = 5;
                   thumbnail.paintIcon(this, g, x, y);
         ImageIcon thumbnail = null;
         File file = null;
         int setHeight, setWidth;
    }Thanks in advance

    Never-mind. I have it working properly now.

  • Animated gifs in applets

    Ive tried to display an animated gif in an applet and it only shows the first frame. What is the code to do this and it be animated?

    IIRC, every time you repaint the applet that contains the gif, the correct frame of the (multi-frame, animated) gif will be rendered.
    So if you create a thread that just calls repaint() every half-second or so, you should see the gif move.
    Usually it isn't necessary to do this explicitly, because there's already a thread updating state and repainting, for some other purpose.

Maybe you are looking for

  • Key date properties popup

    HI all when I refresh the webI report, a pop up with name key date properties is showing up, and once i enter the date value init then it is taking me to prompt window. I just wonder why this popup is showing up, in Bex query properties I don't see a

  • BAPI_ACC_INVOICE_RECEIPT_POST, Accounting Documents grouped?

    Hi there, Hope I'm posting this in the right place. There is a custom program which reads the file from AL11 and then uses BAPI_ACC_INVOICE_RECEIPT_POST to create the invoices. It's creating the invoices but when we view them at tcode KSB1, the drill

  • HP Photosmart 5510 reboots continually

    Hi  My HP Photosmart 5510 started rebooting all of a sudden. Imediatelt its connected to the power source, it powers itself on without pressing the power button but continues rebooting continually. This happens whether its connected to the printer or

  • CONVERTIR REPORTE CR

    Good afternoon, This time I write to you aksing for your help with the following problem. I have a report in CR2008, which with I made a cash receipt with the B1 tables ORCT, RCT1 ETC .. Now I want to take that same report but changing it to the tabl

  • TBD4 - Upload Polish rates in OB08 table

    We currently import daily exchange rates from FINISS to a central SAP server and replicate via ALE to other SAP clients throughout our organization.   We currently load the rates at the end of our business day in the US (16:00).  We are now implement