I am trying to have each of the objects paint themselves into the JPanel by passing graphics through but i am getting a java.lang.NullPointerException error.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JPanel {
private static final long serialVersionUID = 1L;
Main panel;
Player mainPlayer;
public static void main(String[] args) {
JFrame frame = new JFrame("Asteroids");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main panel = new Main();
frame.add(panel);
frame.setBackground(Color.BLACK);
frame.setSize(500, 400);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
mainPlayer.paintComponent(g);
}
}
And then this code is in a different .java file
import java.awt.Graphics;
public class Player {
public Player() {
}
public void paintComponent(Graphics g) {
}
}
Does anyone know why this code isn't working?
It is giving me:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Main.paintComponent(Main.java:23)
2 Answers 2
You are not instantiating mainPlayer. Since the default value is null for uninstantiated object reference variables, you are getting a NullPointerException on line 23 when you are trying to dereference the variable.
1 Comment
The mainPlayer variable is what is causing you problems. You should add in your main method, panel.mainPlayer = new Player(); Because mainPlayer is by default null, you will have to set it to some instance of an object in order to use it and call its methods.
mainPlayeris not initalised any where in your code example