0 votes
1 view
in Java by (8.2k points)

I have a JPanel to which I'd like to add JPEG and PNG images that I generate on the fly.

All the examples I've seen so far in the Swing Tutorials, especially in the Swing examples use ImageIcons.

I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.

  1. Is there any (performance or other) problem in using the ImageIcon class to display an image that size in a JPanel?
  2. What's the usual way of doing it?
  3. How to add an image to a JPanel without using the ImageIcon class?

1 Answer

0 votes
by (41k points)

Here's how it's done (with a little more information on how to load an image):

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...




    protected void paintComponent(Graphics g) {


        g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters            



Welcome to Intellipaat Community. Get your technical queries answered by top developers !