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

前端 未结 2 1855
梦如初夏
梦如初夏 2020-12-18 06:27
Icon icon = new ImageIcon(getClass().getResource( \"/img/icon.gif\" ) );
aButton = new JButton(\"Its a button\", icon);

Is there some kind of metho

相关标签:
2条回答
  • 2020-12-18 07:10

    See:

    • setIcon(Icon)
    • setDisabledIcon(Icon)
    • setPressedIcon(Icon)
    • setRolloverIcon(Icon)
    • setSelectedIcon(Icon)

    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.

    0 讨论(0)
  • 2020-12-18 07:23
    button.setIcon(new ImageIcon("/*icon location*/"));
    button.setRolloverIcon(new ImageIcon("/*icon location*/"
    

    The Animated gif image will not get invisible when mouse pointer moves over the button.

    0 讨论(0)
提交回复
热议问题