首页 文章

动画ImageIcon作为按钮

提问于
浏览
4

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

enter image description here

1 回答

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

相关问题