0

I am having a problem with loading images, as I am trying to load a background for my launcher. It works when I run it in Eclipse, but when I export it to a jar file, it doesn't. I have paged through the already asked questions, No luck.

Here is my code:

public void initializeJFrame(){
    
    ImageIcon bg = new ImageIcon("src/background.png");
    
    jb.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (jta.getText().length() < 3 || jta.getText().length() > 16) {
                System.exit(-1);
            } else {
                try {
                    Runtime.getRuntime().exec(cmd, null, dir);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                System.exit(0);
            }
        }

    });
    jf.setSize(WIDTH,HEIGHT);
    jf.setTitle("Cracked Launcher");
    jf.setLayout(null);
    jf.setContentPane(new JLabel(bg));
    jf.setResizable(false);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
    t.start();

My image is in the src folder, nothing else. I cannot find what the problem is.

Thanks for your support.

image image2

Pale_Gray
  • 37
  • 1
  • 11

1 Answers1

2
ImageIcon bg = new ImageIcon("src/background.png");

This constructor takes a filename; it will not load resources from a jar. You want to pass a URL generated by a classloader, like so:

ImageIcon bg = new ImageIcon(getClass().retResource("background.png"));
OhleC
  • 2,821
  • 16
  • 29