0

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 :(

Arthur
  • 3
  • 1

2 Answers2

0

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().

Queeg
  • 7,748
  • 1
  • 16
  • 42
0

If you access the resource with the path like pics/file_name.png, then the pics - is the package name. And it must be located in the directory, marked as resource type. For example, create the directory, named resources in your project root, mark this directory as resource type, and move the pics there:

enter image description here

P. S. I would advise to use Maven or Gradle build system for managing project builds. As it is commonly accepted build management systems for the JVM projects. IDE New Project Wizard has the option to create Maven or Gradle based projects.

Andrey
  • 15,144
  • 25
  • 91
  • 187
  • Be aware the code in the question does not load from he classpath. Therefore pics is not a package but just a directory. – Queeg Jun 27 '22 at 11:58