java - what calls paintComponent()? -
i attempting draw sprites out of sprite sheet.
i have following class
public class gtcomponent extends jcomponent { graphics2d g2; @override public void paintcomponent(graphics g){ g2 = (graphics2d)g; } public void drawspriteframe(image source, int x, int y, int frame) { int framex = (frame % 12) * 32; int framey = (frame / 12) * 32; g2.drawimage(source, x, y, x + 32, y + 32, framex, framey, framex + 32, framey + 32, this); } }
that created object in main class so
jframe f = new jframe(); gtcomponent img = new gtcomponent(); f.add(img); f.setdefaultcloseoperation(jframe.exit_on_close); f.setsize((int)(i.length * 8.1), (int)(i[0].length * 8.5)); f.setvisible(true); f.setlocationrelativeto(null); bufferedimage test = null; try { test = imageio.read(new file( /*image file path*/)); } catch (ioexception e) { system.out.println("error"); system.exit(0); } img.drawspriteframe(test, (u * 32 + 1), (z * 32 + 1), c);
the problem im facing following error gets thrown
exception in thread "awt-eventqueue-0" java.lang.nullpointerexception
after doing several debugs, setting breakpoints @ paintcomponent
, drawspriteframe
, found out drawspriteframe
method gets called before paintcomponent
method, meaning g2 = null
resulting in error being thrown.
the question here triggers paintcomponent method allows me initialise g2 variable?
paintcomponent()
called automatically event dispatch thread. if want custom component painted part of ordinary swing painting process, should override paintcomponent()
call drawspriteframe()
method, not call drawspriteframe()
directly.
if want control drawing operation yourself, need use "active rendering" as described in full-screen exclusive mode tutorial -- note technique described there works windowed applications. need ask window graphics
instance (instead of waiting 1 passed paintcomponent()
, draw that.
a basic example using double buffering:
// initial setup frame mainframe = new frame(); mainframe.setvisible(true); // you'll want set size, location, etc. mainframe.createbufferstrategy(2); bufferstrategy bufferstrategy = mainframe.getbufferstrategy(); //.... // inside draw loop (call once each frame) graphics2d g2 = (graphics2d) bufferstrategy.getdrawgraphics(); g2.drawimage(...) // etc. g2.dispose(); bufferstrategy.show();
Comments
Post a Comment