Search code examples
javajframejlabelimageicon

Image not being added to panel - Java


I am trying to practice JLabel/JFrame and I am have trouble having my image "key2.png" appear. I am using Visual Studio Code and I have both my code and the image in the same src folder.

`

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JPanel;

class Main {
  public static void main(String[] args) {

    ImageIcon icon = new ImageIcon("key2.png");

    JLabel label = new JLabel();
    label.setText("Hello");
    label.setIcon(icon);

    JPanel redPanel = new JPanel();
    redPanel.setBackground(Color.red);
    redPanel.setBounds(0, 0, 250, 250);

    JPanel bluePanel = new JPanel();
    bluePanel.setBackground(Color.blue);
    bluePanel.setBounds(250, 0, 250, 250);

    JPanel greenPanel = new JPanel();
    greenPanel.setBackground(Color.green);
    greenPanel.setBounds(0, 250, 500, 250);
    
    
    MyFrame myFrame = new MyFrame();   //makes frame
    myFrame.setLayout(null);  //disable defualt layout
    myFrame.add(redPanel);
    redPanel.add(label);   //add text and image to panel
    myFrame.add(bluePanel);
    myFrame.add(greenPanel);
  }
}

`

Output: Output

Expecting to see a black key image in the red panel.


Solution

  • You actually need to put the image into the Project folder. As the Program running directory is not the source directory. Put it into a subfolder like textures and reference it with the path like

    ImageIcon icon = new ImageIcon("textures/key2.png");