ITbot ITbot - 9 months ago 30
Java Question

Image would load in JPanel only after resizing the JFrame

I have a program with 3 panels in the JFrame. One panel serves as a menu, one as a gallery panel and one as a drawing panel. I have a method in drawing panel that makes an image out of the panel and I try to get it to show in the gallery panel.

Reference linking has been made in order for the 3 JPanel classes to communicate and for some reason the resized image only shows when I resize the JFrame (click on the fullscreen button, or resize it in ANY direction.

public void makePanelImage(DrawPanel panel) {
if (galleryPanel.counter <= 12) {
Dimension size = panel.getSize();
BufferedImage myPicture = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = myPicture.createGraphics();
panel.paint(g2);
g2.dispose();

Image img = myPicture.getScaledInstance(150, 150, Image.SCALE_FAST);
JLabel picLabel = new JLabel(new ImageIcon(img));
galleryPanel.add(picLabel);
galleryPanel.counter++;

try {
File file = new File("snapshot" + galleryPanel.counter + ".png");
ImageIO.write(myPicture, "png", file);

} catch (Exception e) {
e.printStackTrace();
}

} else
JOptionPane.showMessageDialog(null, "You cannot add more than 12 images.");

}



  • the if statement is because I want it to be limited to 12 images

  • the try catch block is there because I want it to save it as a screenshot (non-resized) in the soruce code directory (which works btw)

  • the counter variable in gallery panel is there to keep track of how many images (as labels, so components) there are in the panel



Thanks in advance

Answer Source

I have a method in drawing panel that makes an image out of the panel and I try to get it to show in the gallery panel.

When you add a component to a visible frame the basic logic is:

galleryPanel.add(picLabel);
galleryPanel.revalidate(); // invokes layout manager
galleryPanel.repaint();

Unless you invoke the layout manager the component has a size of (0, 0) so there is nothing to paint. Resizing the frame will automatically invoke the layout manager.