Firecat Firecat - 3 months ago 21
Java Question

Image not being displayed in jPanel

So I'm trying to display an image, in a jPanel, within a jFrame.

(I suppose it's that way you display a JPEG/PNG in a jFrame)
Here's what I'm doing:

In the constructor of the jFrame, I download the image, create an ImageIcon, and a jLabel dynamically (set the icon), and insert it in a jPanel.

I have previously created the jPanel with NetBeans IDE, on which jPanelImage is defined in the initComponents().

If I go through the code with the debugger, he downloads the image propery without throwing any exceptions.

It also runs the code properly without any problem.

But my jFrame continues empty.
Here's the code:

public TransmissionFrame() {
initComponents();

init();
}

private void init() {

JLabel label = new JLabel("Java Technology Dive Log");
ImageIcon image = null;
try {
image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png")));
} catch(MalformedURLException mue) {
mue.printStackTrace();
} catch(IOException ioe) {
ioe.printStackTrace();
}
label.setIcon(image);
jPanelImage.add(label);
jPanelImage.validate();
}


But my jFrame and the jPanel are still empty, why?

Answer

update, assigning a layout to your JPanel could be the solution

 public TransmissionFrame() {
        initComponents();

        init();
    }

 private void init() {
JLabel label = new JLabel("Java Technology Dive Log");
ImageIcon image = null;
try {
    image = new ImageIcon(ImageIO.read(new URL("http://i.imgur.com/6mbHZRU.png")));
} catch(MalformedURLException mue) {
    mue.printStackTrace();
} catch(IOException ioe) {
    ioe.printStackTrace();
} 
label.setIcon(image);
jPanelImage.setLayout(new FlowLayout()); 
jPanelImage.add(label);

}
Comments