gpt4 book ai didi

java - 作为按钮的动画 ImageIcon

转载 作者:搜寻专家 更新时间:2023-11-01 02:27:34 25 4
gpt4 key购买 nike

我有一个 imageIcon 作为 Button,现在我会在您滚动时为它设置动画。我尝试在 setRolloverIcon(Icon) 上使用动画 gif(无循环)。但是当我再次将鼠标悬停在按钮上时,gif 不再播放。当我使用循环 gif 时,它会从随机帧播放。我尝试使用 paintComponent 绘制形状或图像作为按钮,效果很好,但即使我使用 setPreferredSize() 或 setSize() 或 setMaximumSize() 按钮也使用其默认大小,如您在图片(中间)中看到的按钮)。我正在使用 GroupLayout,这可能是问题所在吗?

enter image description here

最佳答案

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

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

关于java - 作为按钮的动画 ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18270701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com