I am trying to add an ImageIcon to my JPanel.
ImageIcon image = new ImageIcon("image.png", null);
JLabel label = new JLabel(image, JLabel.CENTER);
panel.add(label);
Ok. The image is is located in the same folder as the class...
com.package
|- mainclass.java
|- image.png
V
For whatever reason, the imageicon will not display in the JPanel. I try/catch-ed it, but no use. No errors at all!
I am on Windows.
ImageIcon(String)
assumes that the specified String value is a file on the file system
Based on you description I would guess that the image is embedded within the application, meaning that it is not longer accessible as a File, but instead needs to accessed as a URL
or InputStream
Because the image and class are in the same package you can use something like
ImageIcon img = new ImageIcon(getClass().getResource("image.png"));
Assuming you're loading it from MainClass
You must specify the full path
, seeing it from the root
of your application.
In your case, you must use new ImageIcon("com/package/image.png", null)
.
EDIT
I looked at some old code with a similar situation turns out I added the image to a JLabel first and then to the JPanel.
Try adding the Image to a JLabel and then add that JLabel to the JPanel as follows.
ImageIcon image = new ImageIcon(this.getClass().getResource("image.png"));
JLabel picLabel = new JLabel(image);
panel.add(picLabel);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.