Search code examples
javaintellij-ideajoptionpaneimageicon

Icons not visible after compilation


ok i am a new one here and tried to write an awesome program:

package f;

import javax.swing.*;

public class dasMain {
    public static void main(String[] args) {
        ImageIcon img = new ImageIcon("pics/daFaq.png");
        JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
    }
}

the thing is that if I run the program from Intellij Idea, then everything works fine, but after compilation the picture disappears

here are the source files of the project: https://i.ibb.co/Njc8jYp/screen.png

i want to run this awesome code with pictures on other computers, but i only know this way and it doesn't work :(


Solution

  • You probably do not know where your program expects the picture to be. If you modify your code slightly, this information would be evident. Make use of

    With that your code can look like this:

    package f;
    import javax.swing.*;
    import java.io.File;
    
    public class dasMain {
        public static void main(String[] args) {
            File png = new File("pics/daFaq.png");
            System.out.println("Loading image from " + png.getAbsolutePath());
            ImageIcon img = new ImageIcon(png.toURI().toURL());
            JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
        }
    }
    

    Also I am pretty sure you intend to ship the png together with your code, so you better load it as a resource from the classpath. Here is an example.

    I also investigated a bit why you would not see any error message or exception. This is documented in ImageIcon. So you might want to verify the image was loaded using getImageLoadStatus().