繁体   English   中英

在JButton上动画GIF,当鼠标悬停时播放它

[英]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);

是否有某种方法可以阻止动画播放? 我正在考虑分配gif的静态jpg,然后当我悬停时,分配动画gif,但我不认为在MouseMotionListener有一个取消鼠标的事件,所以我可以加载回静态jpg。

按钮中的gif循环,但是,如果我将鼠标悬停在按钮上,它就会消失。

如果我的鼠标光标不在按钮上,如何使gif静态?

如果我使用MouseMotionListener ,如果我取下鼠标它会触发事件吗?

@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) {
}

看到:

无需设置显式鼠标侦听器,转换会自动进行。

EG在此示例中,我没有添加MediaTracker因此将图像弹出到标签中以允许加载时间。 最终用户是ImageObserver (等到你在解除第一个对话框之前看到它旋转)。

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

另外,不要将静态图像设为JPEG。 JPEG是有损的,不支持透明度。 使用单帧GIF或PNG。

button.setIcon(new ImageIcon("/*icon location*/"));
button.setRolloverIcon(new ImageIcon("/*icon location*/"

当鼠标指针移过按钮时,动画gif图像将不会被隐藏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM