Search code examples
javaswingjbuttonanimated-gifimageicon

Animated GIF on a JButton, play it when mouse is hovered


Icon icon = new ImageIcon(getClass().getResource( "/img/icon.gif" ) );
aButton = new JButton("Its a button", icon);

Is there some kind of method that can stop an animated from playing? I was thinking of assigning a static jpg of the gif, then when I hover, assign the animated gif, but I don't think there is an event for taking off mouse in MouseMotionListener so I can load back the static jpg.

The gif loops in the button, however, if I hover over it, it disappears.

How can I make the gif static if my mouse cursor is not on the button?

If I use MouseMotionListener, does it fire an event if I take off my mouse?

@Override
public void mouseMoved(MouseEvent e) {
//play the gif
//if I take mouse off, call some method to stop playing animated gif
}

@Override
public void mouseDragged(MouseEvent e) {
}

Solution

  • See:

    No need for setting an explicit mouse listener, the changeover happens automatically.

    E.G. In this example I did not add a MediaTracker so popped the image into a label to allow for load time. The end user is the ImageObserver (wait till you see it spin before dismissing the first dialog).

    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.swing.*;
    
    public class ImageSwapOnButton {
    
        public static void main( String[] args ) throws Exception {
            URL url = new URL("http://1point1c.org/gif/thum/plnttm.gif");
    
            Image image = Toolkit.getDefaultToolkit().createImage(url);
            ImageIcon spinIcon = new ImageIcon(image);
            JOptionPane.showMessageDialog(null, new JLabel(spinIcon));
    
            // create a static version of this icon
            BufferedImage bi = new BufferedImage(150,150,BufferedImage.TYPE_INT_ARGB);
            Graphics g = bi.getGraphics();
            g.drawImage(image,0,0,null);
            g.dispose();
            ImageIcon staticIcon = new ImageIcon(bi);
    
            JButton button = new JButton(staticIcon);
            button.setRolloverIcon(spinIcon);
            JOptionPane.showMessageDialog(null, button);
        }
    }
    

    Also, don't make the static image as JPEG. A JPEG is lossy and does not support transparency. Either use a single frame GIF or a PNG.