JPanel and BufferedImage

18,854

Solution 1

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

Solution 2

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.

Share:
18,854
MQSJ23
Author by

MQSJ23

...

Updated on June 17, 2022

Comments

  • MQSJ23
    MQSJ23 almost 2 years

    How do you display a BufferedImage in a JPanel ?

  • MQSJ23
    MQSJ23 about 11 years
    Thank you, that has helped a lot.
  • Alya'a Gamal
    Alya'a Gamal about 11 years
    You are welcome anytime :)