[英]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. 我正在考虑分配gif的静态jpg,然后当我悬停时,分配动画gif,但我不认为在
MouseMotionListener
有一个取消鼠标的事件,所以我可以加载回静态jpg。
The gif loops in the button, however, if I hover over it, it disappears. 按钮中的gif循环,但是,如果我将鼠标悬停在按钮上,它就会消失。
How can I make the gif static if my mouse cursor is not on the button? 如果我的鼠标光标不在按钮上,如何使gif静态?
If I use MouseMotionListener
, does it fire an event if I take off my mouse? 如果我使用
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) {
}
See: 看到:
setIcon(Icon)
setDisabledIcon(Icon)
setPressedIcon(Icon)
setRolloverIcon(Icon)
setSelectedIcon(Icon)
No need for setting an explicit mouse listener, the changeover happens automatically. 无需设置显式鼠标侦听器,转换会自动进行。
EG In this example I did not add a MediaTracker
so popped the image into a label to allow for load time. EG在此示例中,我没有添加
MediaTracker
因此将图像弹出到标签中以允许加载时间。 The end user is the ImageObserver
(wait till you see it spin before dismissing the first dialog). 最终用户是
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);
}
}
Also, don't make the static image as JPEG. 另外,不要将静态图像设为JPEG。 A JPEG is lossy and does not support transparency.
JPEG是有损的,不支持透明度。 Either use a single frame GIF or a PNG.
使用单帧GIF或PNG。
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. 当鼠标指针移过按钮时,动画gif图像将不会被隐藏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.