动画 ImageIcon 作为按钮 [英] Animated ImageIcon as Button
问题描述
我有一个图像图标作为按钮,现在我会在你翻滚时为它设置动画.我尝试在 setRolloverIcon(Icon) 上使用动画 gif(无循环).但是当我再次将鼠标悬停在按钮上时,gif 不再播放.当我使用循环 gif 时,它会从随机帧播放.我尝试使用paintComponent将形状或图像绘制为按钮,效果很好,但即使我使用 setPreferredSize() 或 setSize() 或 setMaximumSize() 按钮使用其默认大小,如您在图片中看到的(中间按钮).我正在使用 GroupLayout,这可能是问题吗?
I have an imageIcon as Button, now i would to animate it when you rollover. I tried to use a animated gif (without loop) on setRolloverIcon(Icon). But when i hover again on the button the gif is not playing again. When i use a looped gif then it plays it from a random frame. I tried using paintComponent to draw a Shape or an image as Button, which works fine, but even when i use setPreferredSize() or setSize() or setMaximumSize() the Button uses its default size, as you can see in the picture (middle button). Im using GroupLayout, might this be the problem?
推荐答案
似乎对我来说很好用...
Seems to work just fine for me...
我使用了以下图标...(png 和 gif)...
I used the following icons...(png and 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.这意味着您将需要尝试重置"以重新开始播放.
I just realised that you are using a non-looping gif. This means you are going to nee to try and "reset" to start it playing again.
尝试使用诸如 icon.getImage().flush();
之类的东西,其中 icon
是您的 ImageIcon
.您将不得不将 MouseListener
附加到按钮以检测 mouseEnter
事件并重置 ImageIcon
...
Try using something like icon.getImage().flush();
, where icon
is your ImageIcon
. You're going to have to attach a MouseListener
to the button to detect the mouseEnter
event and reset the ImageIcon
...
这篇关于动画 ImageIcon 作为按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!