动画ImageIcon作为按钮

dom*_*zai 4 java swing animated-gif jbutton imageicon

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

在此输入图像描述

Mad*_*mer 5

似乎工作对我来说很好......

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

我使用了以下图标......(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();
                }

            });
        }    
    }
}
Run Code Online (Sandbox Code Playgroud)

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

尝试使用类似的东西icon.getImage().flush();,icon你的位置在哪里ImageIcon.您将不得不附加一个MouseListener按钮来检测mouseEnter事件并重置ImageIcon...