Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.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 (46k 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...

       }

    }

    @Override

    protected void paintComponent(Graphics g) {

        super.paintComponent(g);

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

    }

}

Related questions

0 votes
1 answer
asked Mar 22, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 20, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Nov 19, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...