Deveram
Deveram

Reputation: 460

Why does this simple code not work

I am having trouble with this simple example code from the book. It is supposed to represent the same image 2 times in one window (north and south labels), one above the other. When I run it, it displays this instead of this (I am sorry for not cutting the images or resizing them) Below is my code. I am running Eclipse Juno on Ubuntu 13.04.

package gui;
import java.awt.BorderLayout;
import javax.swing.*;

public class Gui {


    public static void main(String[] args) {

        JLabel northLabel = new JLabel ( "North" );

        ImageIcon labelIcon = new ImageIcon ("GUItip.gif");

        JLabel centerLabel = new JLabel (labelIcon);
        JLabel southLabel = new JLabel (labelIcon);

        southLabel.setText("South");
        JFrame application = new JFrame();

        application.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

        application.add(northLabel, BorderLayout.NORTH);
        application.add(centerLabel, BorderLayout.CENTER);
        application.add(southLabel, BorderLayout.SOUTH);

        application.setSize(300, 300);
        application.setVisible(true);


    }

}

Upvotes: 0

Views: 196

Answers (2)

Mady
Mady

Reputation: 653

You need to concentrate on the following statement:

ImageIcon labelIcon = new ImageIcon ("GUItip.gif");

When initiating new ImageIcon.. it searches the provided address in execution folder by default i.e. in this case "GUItip.gif" shall be searched within workspace/user directory.

One solution is to make available GUItip.gif image in you workspace (program execution) folder. Another solution would be to provide absolute path.. eg.

C:\USER\Workspace\project_name\GUItip.gif

Though a better approach would be to create a specific folder where you save all images used in your project. Create a final static String variable with absolute path to your folder. Now it would be easy for any programmer in that project to know where to look for images. There are good approaches to use this mapping.. through XML to be loaded in the beginning.. through resourcebundle etc but that is a different topic altogether.

Upvotes: 2

JZachow
JZachow

Reputation: 187

The image probably isn't loading properly. Try using a try/catch block to see if that's the case.

Ex:

   Image img;

    File f = new File(//image url);
    try {
        img = ImageIO.read(f);
    } catch (IOException e) {
        String curr_dir = System.getProperty("user.dir");
        throw new IllegalArgumentException("Image could not be found from " + curr_dir);
    }
   ImageIcon labelIcon = new ImageIcon(img);

Upvotes: 0

Related Questions