8

In the overridden function for my JFrame:

@Override
protected void paintComponent(Graphics g) {

    BufferedImage imagePerson;
    try {
        imagePerson = ImageIO.read(new File("errol.gif"));
    } catch (IOException e) {
        imagePerson = null;
    }

    g.drawImage(imagePerson, i * increment, j * increment - 1, null);
}

How can I change this so the animation on the gif is shown (without using threading). I have spent many hours trying to get this to work but to no avail.

dacwe
  • 43,066
  • 12
  • 116
  • 140
Yawn
  • 519
  • 4
  • 7
  • 18
  • 5
    Regardless of which solution you pursue, you probably don't want to actually be *loading* images each time `paintComponent` is called. That method is a called a **lot**. Load them once at initialization and store them in an instance variable of your class. – Mark Peters Dec 02 '10 at 22:01

2 Answers2

5

You could use an ImageIcon for this purpose. Have a look here and here. If you need the animation on a JPanel, simply add a JLabel (with the ImageIcon) to the panel.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • The thing is I want to move the position of the animated gif around the jpanel with positions worked out in :protected void paintComponent(Graphics g) { – Yawn Dec 02 '10 at 19:52
  • and I can't see a way of adding a jlabel to the jpanel in that function – Yawn Dec 02 '10 at 19:53
  • Either you move your ImageIcon around, or you set up a Timer that calls repaint repeatedly, and figure out where and which frame to draw in your paintComponent method. – aioobe Dec 02 '10 at 20:01
  • 2
    Add the label to the panel. Then to move the label you simply invoke setLocation(). There is no need to override the paintComponent() method or call repaint(). – camickr Dec 02 '10 at 21:17
1

Check this example for displaying an animated gif in Swing. you dont have to use any threads:

Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);

Source

Mehdi
  • 1,340
  • 15
  • 23