-1

The problem is that the image is not getting loaded while I run the following swing program. I have a package called "sWINGPRAC" inside which I have a JAVA file IconLabelDemo.java. I have ensured that the Image "myIcon.gif" is in the same directory. myIcon.gif IconLabelDemo.java.

package sWINGPRAC;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;


public class IconLabelDemo {

        public IconLabelDemo() {

            JFrame jfrm = new JFrame("ImageIcon");
            jfrm.getContentPane().setLayout(new GridLayout(4, 1));
            jfrm.setSize(250, 300);
            jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            ImageIcon img = new ImageIcon("myIcon.gif");

            JLabel jlabIcon = new JLabel(img);

            JLabel jlabIconTxt = new JLabel("Default iCon and text position",img , SwingConstants.CENTER);

            JLabel jlabIconTxt2 = new JLabel("Text left of icon",img,SwingConstants.CENTER);
            jlabIconTxt2.setHorizontalTextPosition(SwingConstants.LEFT);

            JLabel jlabIconTxt3 = new JLabel("Text Over ICon",img,SwingConstants.CENTER);
            jlabIconTxt3.setVerticalTextPosition(SwingConstants.TOP);


            jfrm.add(jlabIcon);
            jfrm.add(jlabIconTxt);
            jfrm.add(jlabIconTxt2);
            jfrm.add(jlabIconTxt3);

            jfrm.setVisible(true);

        }
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {

                    new IconLabelDemo();

                }
            });
        }
}
faizal vasaya
  • 517
  • 3
  • 12

1 Answers1

3

Nadir has hit the nail on the head with his comment. You are using "myIcon.gif" as a filename, which means it has to be local to the directory where the program is executed. If you want to package the icon with your library, you need to look into using resource loaders. Have a look at this question: How to correctly get image from 'Resources' folder in NetBeans (it should apply in Eclipse also).

Community
  • 1
  • 1
Jane Nicholson
  • 375
  • 2
  • 12