动画(循环)GIF 可以显示在JLabel
或者在 HTML 中(在格式化文本组件中,例如JEditorPane
)并被视为循环。
但是要加载图像以绘制为容器的背景,我通常会使用ImageIO.read()
or Toolkit.getImage()
(后者当我怀念上个千年时)。加载图像的方法都不会产生循环图像,它通常只是第一帧。
如何加载animated背景图像?
E.G.
要获取用于自定义绘画的循环(动画)GIF,一个技巧是使用ImageIcon
。虽然从问题中列出的两种方法之一返回的图像是静态的,但从ImageIcon
是动画的。
The code below will add 50 buttons, then soon after the frames of the 'zooming stars' animated GIF1 as BG to them. The ImagePanel
will stretch the image to the size of the panel.
- 它是基于这个图像。
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
class ImagePanel extends JPanel {
private Image image;
ImagePanel(Image image) {
this.image = image;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,0,0,getWidth(),getHeight(),this);
}
public static void main(String[] args) throws Exception {
URL url = new URL("https://i.stack.imgur.com/iQFxo.gif");
final Image image = new ImageIcon(url).getImage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame("Image");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
ImagePanel imagePanel = new ImagePanel(image);
imagePanel.setLayout(new GridLayout(5,10,10,10));
imagePanel.setBorder(new EmptyBorder(20,20,20,20));
for (int ii=1; ii<51; ii++) {
imagePanel.add(new JButton("" + ii));
}
f.setContentPane(imagePanel);
f.pack();
f.setVisible(true);
}
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)