How can an animated (cycling) GIF be loaded and displayed as the background for a Swing container, as opposed to the static image loaded using ImageIO.read() or Toolkit.getImage()?
To obtain an animated GIF for custom painting, use an ImageIcon rather than ImageIO or Toolkit. ImageIcon provides an animated image, unlike the static image returned by the other methods.
The following code snippet illustrates how to load an animated GIF and use it as the background for a 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.sstatic.net/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); } }); } }
In this code:
Run this code to see the animated GIF displayed as the background.
The above is the detailed content of How to Display an Animated GIF as a Swing Container Background?. For more information, please follow other related articles on the PHP Chinese website!