No picture shown in window


I am a college student taking a Java course, and i'm having difficulty understanding what's wrong with my program. The pupose of the program is to display a picture in a window. The window shows up but with no picture. I tried replacing the JLabel object containing the picture with one that contains a string, and when i did this, the program worked fine. However when I switched back to the picture, no picture would show in the window. I don't know what to do. Can anyone help me!
Below is a copy of the code

import javax.swing.*;
import java.awt.*;
class Card1 {
public static void main(String[] args) {

//Prepares for the cereation of a new top-level window variable and names it "myWindow"
JFrame myWindow;
//creates a display area called "greeting" which displays a string
JLabel greeting = new JLabel ("This is my first java program");
ImageIcon pic = new ImageIcon("koala.jpeg");
JLabel mypic = new JLabel(pic);
greeting.setFont (new Font ("Helvetica",
Font.PLAIN+Font.BOLD+Font.ITALIC, 36));
myWindow = new JFrame();//Constructs the new top-level window
myWindow.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
myWindow.setSize(500, 500);
myWindow.setTitle("My First Java Program");
myWindow.getContentPane().add (mypic);
//myWindow.getContentPane().add (pic);


  • Hey,
    I believe the problem is the "file spec" of the picture is not found by the JVM. The easy solution, provide the full file spec. ie. something like this, (this is file spec for a jpeg I had on my machine) [code]ImageIcon pic = new ImageIcon("C:\Java Coding\Eclipse\NonSpecificProject\appClientModule\Penguins.jpg");[/code]
    Note the use of double backward slashes. I am running on a Windows machine which uses a backslash to separate directories. However the backslash is also an escape character for Java. Thus to tell Java to "see" a backslash, it takes 2 backslashes - the first is the Java escape character and the second is then interpreted as a backslash.

    regards, se52
  • just put your picture in the project root and the file will be found and displayed in your jframe. if your file must be loaded from an other folder you must provide the full path to that file.

    and if you want to display the pic and the greetings you can add the following two lines to your code

    myWindow.getContentPane().add(mypic, BorderLayout.CENTER);
    myWindow.getContentPane().add(greeting, BorderLayout.SOUTH);
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!