问题描述
Icon icon = new ImageIcon(getClass().getResource( "/img/icon.gif" ) );
aButton = new JButton("Its a button", icon);
是否有某种方法可以阻止动画播放?我正在考虑分配 gif 的静态 jpg,然后当我悬停时,分配动画 gif,但我认为 MouseMotionListener
中没有用于关闭鼠标的事件,因此我可以重新加载静态 jpg.
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.
按钮中的 gif 循环,但是,如果我将鼠标悬停在它上面,它就会消失.
The gif loops in the button, however, if I hover over it, it disappears.
如果鼠标光标不在按钮上,如何使 gif 静态化?
如果我使用 MouseMotionListener
,如果我取下鼠标,它会触发一个事件吗?
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) {
}
推荐答案
参见:
无需设置显式鼠标监听器,自动切换.
No need for setting an explicit mouse listener, the changeover happens automatically.
E.G.在此示例中,我没有添加 MediaTracker
,因此将图像弹出到标签中以留出加载时间.最终用户是 ImageObserver
(在关闭第一个对话框之前等待它旋转).
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);
}
}
另外,不要将静态图像设为 JPEG.JPEG 是有损的,不支持透明度.使用单帧 GIF 或 PNG.
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.
这篇关于JButton 上的动画 GIF,在鼠标悬停时播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!