在JButton上动画GIF,在鼠标hover时播放它

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

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

然而,按钮中的gif循环,如果我将鼠标hover在按钮上,它就会消失。

如果我的鼠标光标不在按钮上,如何使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) { } 

看到:

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

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

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://sofzh.miximages.com/java/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图像将不会被隐藏。