0

So, I do not know why my image is not showing because I put the image in the right folder and I believe that the code below is right. The result of this code is just a blank white frame background. I thought the image was corrupted but I tried a different image and its the same result. Anyway I will be highly grateful if anyone could solve this.

package fia_project;
import java.awt.Color;
java.awt.*;
import javax.swing.*;



     public class Fia_test extends JFrame {
     public Frame kenny;

    public Fia_test(){
    super("");

    setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    setVisible(true);
    setSize(350, 100); 
    Container pane = getContentPane();
    getContentPane().setBackground(Color.WHITE); 

    ImageIcon icon = new ImageIcon("speaker.png");
    JLabel label2 = new JLabel(icon);
    add(label2);
       }


    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
    // TODO code application logic here
    Fia_test t = new Fia_test();


  }
  }

1 Answers1

2

Use ImageIO.read instead of ImageIcon as it will generate an error if the image can not be loaded, much more useful for diagnostics. See Reading/Loading an Image

ImageIcon(String) expects that the specified String represents a file on the file system. From the looks of you code, it is possible that you've placed the image within the source directory of your code.

Assuming that the image has been bundled into the resulting Jar file, you will no longer be able to access the image as if it was a file on the file system, but will need to use Class#getResource to load it...

For example...

BufferedImage img = ImageIO.read(getClass().getResource("speaker.png"));
ImageIcon icon = new ImageIcon(img);

Assuming that speaker.png is in the same directory as the class file.

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366