动画ImageIcon作为按钮

时间:2013-08-16 09:59:25

标签: java swing jbutton animated-gif imageicon

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

enter image description here

1 个答案:

答案 0 :(得分:5)

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

enter image description here enter image description here

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

enter image description here enter image description here

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 ...