Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing an image using JPanel

I have written my own ImagePanel using one of previous topics here:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class ImagePanel extends JPanel{

    private BufferedImage image = null;

    public ImagePanel(BufferedImage im) {
       image = im;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);            
    }
}

And then I thought it would be nice to add this panel on the normal JPanel(it would be easier to put it on the frame using this all NetBeans stuff). So I added one, NetBeans generated me some code: private javax.swing.JPanel pnlImagePanel; And here it comes the moment when I would like to show image, so:

File selectedFile = new File(path);
try {
       image = ImageIO.read(selectedFile);
} catch(IOException ex) {
       throw new RuntimeException(ex);
}
ImagePanel imPanel = new ImagePanel(image);
this.pnlImagePanel = imPanel;
this.pnlImagePanel.repaint();

Problem is obvious - I got no result. Shouldn't it work? I've overriden the method paintComponent, so polymorphism should fire. Or is something missing to me?

like image 326
Fuv Avatar asked Jul 24 '26 21:07

Fuv


2 Answers

Just assigning an member variable pnlImagePanel to your ImagePanel will not work, you would have to add the panel to the JPanel container:

pnlImagePanel.add(imPanel);

You will need to give imPanel a size so that the image can be seen. The easiest approach would be to use a layout manager that allows the child panel occupy the maximum area. Rather than the default FlowLayout, you could use GridLayout:

pnlImagePanel.setLayout(new GridLayout());

Calling repaint is unnecessary here. The paint chain mechanism will ensure that your panels are painted.

like image 168
Reimeus Avatar answered Jul 26 '26 10:07

Reimeus


Override getPrefferedSize() in ImagePanel to return image size, ie:

    @Override
    public Dimension getPreferredSize() {
        if (image == null) {
            return super.getPreferredSize();
        }
        return new Dimension(image.getWidth(this), image.getHeight(this));
    }

And, yes, don't forget to add the image panel to the container as suggested by @Reimeus. +1 to him.

like image 38
tenorsax Avatar answered Jul 26 '26 11:07

tenorsax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!