Java Swing: Why can't I drawImage() on an instance of JFrame? -
without going grave detail, i'm working toward creating desktop-like program in swing, icons drawn on top of background image. subclass jpanel or jcomponent , draw on that, wanted try new kicks, , tried drawing on instance of jframe, without making program subclass of it.
i aware not accepted way of doing this, discovering image not drawn has exposed missing link (one of many, suppose) in understanding of swing , how paints components.
what confuses me if program subclasses jframe , override paint() method (the accepted way, in other words), draw image jframe, not instance of jframe in non-subclassed program.
hopefully code showing want help:
public class imageloader { bufferedimage img = null; jframe window = null; public imageloader() { try { img = imageio.read(new file("src/strawberry.jpg")); }catch(ioexception e) { e.printstacktrace(); } window = new jframe("strawberry viewer"); window.setdefaultcloseoperation(jframe.exit_on_close); window.pack(); window.setvisible(true); //why can't akin following draw on instance of jframe? graphics g = window.getgraphics(); paint(g); } public void paint(graphics g) { g.drawimage(img, 0, 0, null); } public static void main(string[] args) { new imageloader(); } }
i have read oracle's page "painting in awt , swing" i'm still not understanding why can't draw on instance of jframe. there situation draw on instance of component, or have subclassed if want draw on them?
finally, if problem based largely on gross misunderstanding of how swing works, recommended books or other resources understanding swing?
thanks in advance. appreciate it.
don't use getgraphics() painting.
anything graphics object temporary. next time swing determines frame needs repainted lose painting.
in case use pack() frame minimized. when resize frame, normal frame painting paint on image. try using setsize(500, 500);
.
however won't work because image painting before normal painting has completed. not code executed sequentially.
try following delay painting of image:
try { thread.sleep(1000); graphics g = window.getgraphics(); paint(g); } catch(exception e) { e.printstacktrace(); }
when image shows, try resizing frame , lose image.
if program subclasses jframe , override paint() method
don't override paint() of jframe (yes, work, not way painting designed done in swing). custom painting done overriding paintcomponent() of jpanel , add panel frame.
if problem based largely on gross misunderstanding of how swing works
the swing tutorial best place start swing basics. see section on custom painting started.
for more technical article see painting in awt , swing.
Comments
Post a Comment