JPanel and BufferedImage
18,854
Solution 1
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.
Comments
-
MQSJ23 almost 2 years
How do you display a BufferedImage in a JPanel ?
-
MQSJ23 about 11 yearsThank you, that has helped a lot.
-
Alya'a Gamal about 11 yearsYou are welcome anytime :)