skip to Main Content

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.

3

Answers


  1. Try replacing new ImageIcon("key2.png") with

    new ImageIcon(Main.class.getResource("key2.png"))
    

    and make sure your key2.png image file is copied into the directory that contains the Main.class file before running your application.

    Class.getResource finds application resource files and should be used for files that are meant to be distributed with the application. See the getResource API documentation for more details.

    Login or Signup to reply.
  2. Since you are using JPanel and working with spring try the below method which turns the image to a swing component. Hence it becomes subject to layout conditions like any other component:

    BufferedImage myPicture = ImageIO.read(new File("path-to-file"));
    JLabel picLabel = new JLabel(new ImageIcon(myPicture));
    add(picLabel);
    
    Login or Signup to reply.
  3. 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");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search