java - Cannot display image with correct path using ImageIcon -
i've been having issue displaying images in java imageicon class. code simple, displays window
.
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
.
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
Post a Comment