Skip to main content

Example almost straight out of book doesnt display images

Please note these forums are being decommissioned and use the new and improved forums at
1 reply [Last post]
Joined: 2011-04-12

This little bit of code is almost straight out of Horstmanns Core Java except I did it in netbeans with the gui builder. But there's hardly anything to it. I know it finds the image because it prints the right width. But the frame displays nothing at all. What did I do wrong??

package my.stuff;

import java.awt.*;
import javax.imageio.*;
import javax.swing.*;

public class jarredImages extends JFrame
Image image = null;

public jarredImages()
ImagePanel imagePanel = new ImagePanel();

private class ImagePanel extends JPanel
private Image image;

public ImagePanel()
URL url = jarredImages.class.getResource("/s2000.jpg");
try { image =; }
catch (Exception ee) { ee.printStackTrace(); }
System.out.println("width = " + image.getWidth(this));

public void paintComponent(Graphics g)
if (image == null) return;

int width = image.getWidth(this);
int height = image.getHeight(this);

g.drawImage(image, 1, 1, null);

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {


                javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                        .addGap(0, 400, Short.MAX_VALUE)
                        .addGap(0, 300, Short.MAX_VALUE)

        }// </editor-fold>

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jarredImages().setVisible(true);

        // Variables declaration - do not modify
        // End of variables declaration


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2011-04-11

The way you set up the GroupLayout and/or how you add the ImagePanel is wrong:
If I use a simple BorderLayout and add the ImagePanel to its CENTER it properly displays the graphics.
I am not used to working with those layout groups but don't we have to add components to groups or such (rather than to the container)? Or at least specify some layout constraints upon adding? Research/experiment in that direction and you'll certainly find it out.