I am attempting to draw sprites out of a sprite sheet.
I have the 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 is created as an object in the main class as 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 is that the following error gets thrown
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
After doing several debugs, setting breakpoints at paintComponent
and drawSpriteFrame
, i found out that the drawSpriteFrame
method gets called before the paintComponent
method, thus meaning that g2 = null
resulting in that error being thrown.
The question here is what triggers the paintComponent method which allows me to initialise the g2 variable?