To display an animated GIF in a Java app, you can use the javax.swing.JLabel
class and set the GIF image as the label's icon.
Here is an example of how to do this:
import javax.swing.*; import java.awt.*; public class AnimatedGifExample extends JFrame { public AnimatedGifExample() { // Set the frame's size and title setSize(400, 300); setTitle("Animated GIF Example"); // Set the layout to a border layout setLayout(new BorderLayout()); // Create a label with the GIF image as its icon ImageIcon icon = new ImageIcon("animated.gif"); JLabel label = new JLabel(icon); // Add the label to the frame's content pane add(label, BorderLayout.CENTER); } public static void main(String[] args) { // Create a new frame and make it visible JFrame frame = new AnimatedGifExample(); frame.setVisible(true); } }
In this example, the GIF image is assumed to be in the same directory as the AnimatedGifExample
class. You can also use a file path or a URL to specify the location of the GIF image.
Note that the JLabel
class supports only a limited number of GIF features, such as transparency and frame delays. If you need to display a more complex GIF or need more control over the animation, you can use the java.awt.MediaTracker
class or the javax.swing.Timer
class to create a custom animation.