Search code examples
javaeclipseswingembedded-resource

Java swing: trouble understanding adding image to JLabel


I hope everyone is doing alright this fine day.

I'm learning swing and I was confused by how to reference an image. I understand that I should use a JLabel and then add that JLabel to the Frame using this.add();, but even looking at the oracle documentation here:

https://docs.oracle.com/javase/6/docs/api/javax/swing/ImageIcon.html

It is still unclear how to reference a file without giving the entire path like

C:\Users\someUser\eclipse-workspace\andSoOn.png

And I can't do that. I have to send my work to my teacher once I'm done, and the code won't reference the file like it does on my system. I tried several things, and I ended up making a new folder in the src in eclipse called ImageAssets and moving the files there, but nothing seems to work. Here is what it looks like

I added a folder called ImageAssets

Here is an example of my attempt to display an image from within the package.

import java.awt.*;
import javax.swing.*;

public class Hangman extends JFrame
{
        JButton playGameButton,
                OptionsButton;
        private ImageIcon hangman7;
        private JLabel mainLabel;

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

        public Hangman()
        {
            this.setSize(1000,800);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setTitle("Hangman");
            this.setResizable(false);
            playGameButton = new JButton("Start Game");
            OptionsButton = new JButton("Options");

            //hangman7 = new ImageIcon(getClass().getResource("Images\\ hangman7.png"));//just an attempt at something
            mainLabel = new JLabel();
            mainLabel.setIcon(new ImageIcon("hangman7.png"));


            JPanel somePanel = new JPanel();
            somePanel.setLayout(new BorderLayout());
            somePanel.add(playGameButton, BorderLayout.WEST);
            somePanel.add(OptionsButton, BorderLayout.EAST);
            somePanel.add(mainLabel, BorderLayout.CENTER);

            this.add(somePanel);
            this.validate();
        }

Thank you so much for taking the time to help me. I tried to be very detailed; if anything is unclear please ask.


Solution

  • In your case, you want let the class loader find the resource, like this:

    mainLabel.setIcon(
        new ImageIcon(getClass().getResource("/ImageAssets/hangman7.png")));