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
Try replacing
new ImageIcon("key2.png")
withand make sure your
key2.png
image file is copied into the directory that contains theMain.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.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:
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