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);


    }

}

Answers


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.


Need Your Help

Join two lists into one list

c# list table join lambda

I have two lists from two different tables; the lists are from different dbs and I need to join or create a new list with the result of the two list(tables), where the value from list 2 are equals ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.