0

i want to draw a gif image in my panel,the problem is that my code draws jpg images fine but i does not draw gif images.This is how my code looks like.

public class DrawingPanel extends JPanel {
Image image;

public DrawingPanel() {
    setPreferredSize(new Dimension(600,600));
    setBackground(Color.CYAN);
    image = new  ImageIcon("C:\\Users\\Hp\\Downloads\\loading.gif").getImage();
}

@Override
    protected void paintComponent(Graphics g) {
    // TODO Auto-generated method stub
    super.paintComponent(g);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Usman Naseer
  • 60
  • 10
  • Did you even try to google or search on this site? [First hit on google](http://stackoverflow.com/questions/2935232/show-animated-gif-in-java). "Animated Gif Java" – brimborium Oct 30 '15 at 18:24
  • Why is this using custom painting for the image instead of displaying it in a label (which should automatically animate it)? 1) See also [Show an animated BG in Swing](http://stackoverflow.com/q/10836832/418556) 2) `g.drawImage(image, 0, 0, getWidth(), getHeight(), null);` should be `g.drawImage(image, 0, 0, getWidth(), getHeight(), this);` – Andrew Thompson Oct 30 '15 at 18:25
  • I am using paintComponent because i have to draw a grid.and i want gif image in the background, like flow free game – Usman Naseer Oct 30 '15 at 18:27
  • Then see the details in 'Show an animated BG in Swing'! – Andrew Thompson Oct 30 '15 at 18:30
  • i did and it helped,thanks @andrewthomson – Usman Naseer Oct 30 '15 at 18:40

1 Answers1

0
BufferedImage image;
image = ImageIO.read(new File("image name and path"));

Use ImageIO

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, null);    
}
SatyaTNV
  • 4,137
  • 3
  • 15
  • 31