java - Cannot display image with correct path using ImageIcon -


i've been having issue displaying images in java imageicon class. code simple, displays window

this.

 import javax.swing.*;  public class testbuttonicons {     public static void main(string[] args) {         imageicon usflag = new imageicon("images/usflag.png");         jframe frame = new jframe();         jbutton jbt = new jbutton(usflag);         frame.add(jbt);         frame.setsize(500, 500);         frame.setlocationrelativeto(null);         frame.setdefaultcloseoperation(jframe.exit_on_close);         frame.setvisible(true);     } } 

my image located under src folder, , ide can detect it, since shows

this.

also, if change path mentioned above full path, like

"/users/mac/documents/java tb/imageicons/src/images/usflag.png"

the program works normally.

any appreciated.

thanks!

imageicon(string) assumes image located on disk somewhere. when place image inside src directory, ide's bundle image resulting jar (aka embedded resource), means no longer "file" on disk, byte stream in zip file, need access them differently.

start using imageio.read, unlike imageicon, throw ioexception when image can't loaded.

you need use class#getresource or class#getresourceasstream depending on how need reference it, example...

bufferedimage image = null; try {     image = imageio.read(getclass().getresource("/images/usflag.png")); } catch (ioexception ex) {     ex.printstacktrace(); } 

take @ reading/loading image more details


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -