0

I'm having difficulties linking my "fish.png" image so that it can appear in a JFrame. Here's a bit of code that I've modified from online:

package evolution;

import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Image extends JFrame {

    public Image() {

        this.getContentPane().setLayout(new FlowLayout());
        JLabel label1 = new JLabel("Example Text");
        ImageIcon icon = new ImageIcon("fish.png");
        JLabel label2 = new JLabel(icon);

        add(label1);
        add(label2);
    }

    private static void createAndShowGUI() {

        JFrame frame = new Image();
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        createAndShowGUI(); 
    }
}

The "Example Text" label appears, so I know the JFrame works. I've put the same "fish.png" in the src folder (where this class is) and one level up in the main folder (where the src folder is), but the JFrame only shows the text label and not the image. How can I link this properly?

1
  • If the image file is inside the src package, then you should be using Class#getResource, as the image will no longer accessible as a file from the file system, which ImageIcon(String) expects. Based on your example, I oils suggest placing the image in the evolution directory, along with your Image class. Beware that Java.awt.Image already exist, so it could confuse matters if you're not careful Commented Oct 12, 2015 at 0:27

2 Answers 2

2

Use:

ImageIcon icon = new ImageIcon(getClass().getResource("fish.png"));

Put the fish.png file right next to your source file (really the class file). This works even if it is inside a jar file if you include it.

Sign up to request clarification or add additional context in comments.

4 Comments

I put fish.png in the same folder as the class file, and it gave me a null pointer exception. I then copied it into the package (in Eclipse), and now it runs but still shows only the text. :/
Maybe, I remember wrong, but I guess that the picture file has to be in the source package and not inside the output package. That means where the *.java files are and not the *.class files.
I copied the image file into the src folder, the bin folder, and the main folder that contains the src and bin folder just to cover all bases. Still nothing.
You need to havet it in the same directory as the class file for that class. Including package if any.
0

Find the directory in which Eclipse stores your project files and put the image in that directory. I tried it and worked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.