java - Need help setting the background image using JLabel? -
i started gui programming in java , having trouble setting background image jframe
using jlabel
. have read many answers same question on website code complicated beginner.
my source code follows , image i'm using in src
folder (i output window there no image in it):
public class staffgui extends jframe { private jlabel imagelabel = new jlabel(new imageicon("staff-directory.jpg")); private jpanel bxpanel = new jpanel(); public staffgui(){ super("staff management"); bxpanel.setlayout(new gridlayout(1,1)); bxpanel.add(imagelabel); this.setlayout(new gridlayout(1,1)); this.add(bxpanel); this.setvisible(true); this.setdefaultcloseoperation(jframe.exit_on_close); this.setlocationrelativeto(null); this.setresizable(false); this.pack(); }
imageicon(string)
"creates imageicon specified file". actual physical image loaded in background thread, though call might return immediately, loading still running in background.
this means imageicon
not throw errors if image can't loaded, making annoying work with. prefer use imageio.read
possible, throw ioexception
when can't read image reason.
the reason image not loading because image doesn't exist context of jvm, looking in current working directory of image.
when included resources within context of program, can no longer addressed files , need loaded through use of class#getresource
or class#getresourceasstream
, depending on needs.
for example
imagelabel = new jlabel(getclass().getresource("/staffdirectory/staff-directory.jpg"));
where possible, should supply path image context of source root
can give example how can use "imageio.read" in code?
import java.awt.gridlayout; import java.awt.image.bufferedimage; import java.io.ioexception; import javax.imageio.imageio; import javax.swing.imageicon; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; public class staffgui extends jframe { private jlabel imagelabel; private jpanel bxpanel = new jpanel(); public staffgui() { super("staff management"); imagelabel = new jlabel(); try { bufferedimage img = imageio.read(getclass().getresource("/staffdirectory/staff-directory.jpg")); imagelabel.seticon(new imageicon(img)); } catch (ioexception ex) { ex.printstacktrace(); } bxpanel.setlayout(new gridlayout(1, 1)); bxpanel.add(imagelabel); this.setlayout(new gridlayout(1, 1)); this.add(bxpanel); this.setvisible(true); this.setdefaultcloseoperation(jframe.exit_on_close); this.setlocationrelativeto(null); this.setresizable(false); this.pack(); } }
Comments
Post a Comment