I want to display an image inside a panel. So I pass the path of the image to this method, open image file and pass it to the method of a private class dedicated to draw image inside the panel. The problem is the panel remains empty all the time and doesn’t display anything.
Here is the code:
JPanel ImagePane; // I want to add image to this
public void getImagePath(String Path)
{
BufferedImage image = null;
try
{
image=ImageIO.read(new File(Path));
}
catch (IOException e)
{
e.printStackTrace();
}
DisplayImage display= new DisplayImage();
display.getImage(image);
}
private class DisplayImage extends JPanel
{
private BufferedImage image=null;
public void getImage(BufferedImage im)
{
image=im;
repaint();
}
public void paintComponents(Graphics g)
{
g.drawImage(image, 0, 0, image.getWidth() /2, image.getHeight()/2,ImagePane);
}
}
What am I missing?
paintComponentsis a method of theContainerwhich is used to paint each of the components in the container. Instead you needpaintComponentto paint this single component.Change your
method to
Notice the use of the
@Overrideannotation to help with method signature checking.Also calling
will update child components.
In your method
getImagePathyou don’t appear to add theDisplayImageto any container. Instead you create a localDisplayImage, but don’t use it.