2

How do you display a BufferedImage in a JPanel ?

cladelpino
  • 337
  • 3
  • 14
MQSJ23
  • 107
  • 2
  • 2
  • 6

2 Answers2

6

Try this :

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImagePanel extends JPanel{

private BufferedImage image;

public ImagePanel() {
   try {                
      image = ImageIO.read(new File("image name and path"));
   } catch (IOException ex) {
        // handle exception...
   }
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters            
}

}

and try to read this Example to display BufferedImage as ImageIcon

Community
  • 1
  • 1
Alya'a Gamal
  • 5,624
  • 19
  • 34
1

I'm not sure right now but I believe you need to do an

BufferedImage image = ImageIO.read(new File("image path"));
ImageIcon img = new ImageIcon(image);
img.setVisible(true);
add(img);

inside the constructor. I cant remember right now and I dont have the compiler to hand to test but thats how I add images to the panel normaly and the just call super.repaint(); as needed.

Edit: I believerepaint(); will do the job too.

Alya'a Gamal
  • 5,624
  • 19
  • 34