动画ImageIcon作为按钮

我有一个imageIcon作为Button,现在我想在翻转时为它设置动画。 我试图在setRolloverIcon(Icon)上使用动画gif(没有循环)。 但当我再次hover在按钮上时,gif不再播放了。 当我使用循环gif然后它从随机帧播放它。 我尝试使用paintComponent将Shape或图像绘制为Button,它工作正常,但即使我使用setPreferredSize()或setSize()或setMaximumSize(),Button也会使用其默认大小,如图所示(中间)按钮)。 我使用GroupLayout,这可能是问题吗?

在此处输入图像描述

似乎对我来说工作得很好……

在此处输入图像描述在此处输入图像描述

我使用了以下图标……(png和gif)…

在此处输入图像描述在此处输入图像描述

import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.GridBagLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class AnimatedButton { public static void main(String[] args) { new AnimatedButton(); } public AnimatedButton() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { } catch (InstantiationException ex) { } catch (IllegalAccessException ex) { } catch (UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private ImageIcon animatedGif; public TestPane() { setLayout(new GridBagLayout()); JButton btn = new JButton(new ImageIcon("WildPony.png")); btn.setRolloverEnabled(true); animatedGif = new ImageIcon("ajax-loader.gif"); btn.setRolloverIcon(animatedGif); add(btn); btn.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { animatedGif.getImage().flush(); } }); } } } 

我刚刚意识到你使用的是非循环gif。 这意味着您将尝试“重置”以重新开始播放。

尝试使用像icon.getImage().flush(); ,其中icon是您的ImageIcon 。 您将不得不将MouseListener附加到按钮以检测mouseEnter事件并重置ImageIcon