繁体   English   中英

动画ImageIcon作为按钮

[英]Animated ImageIcon as Button

我有一个imageIcon作为Button,现在我会在翻转时为其设置动画。 我试图在setRolloverIcon(Icon)上使用动画gif(没有循环)。 但当我再次悬停在按钮上时,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 ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM