1

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)
tenorsax
21.3k9 gold badges64 silver badges110 bronze badges
asked Aug 15, 2012 at 2:52
5
  • Lets start with the fact that mainPlayer is not initalised any where in your code example Commented Aug 15, 2012 at 3:00
  • I do not feel very smart right now... Commented Aug 15, 2012 at 3:20
  • Don't worry, it happens to the best of us. Commented Aug 15, 2012 at 3:22
  • Welcome to the world of programming, where smart people are made to feel dumb ;) Commented Aug 15, 2012 at 3:24
  • Haha, I think i'm going to like it here. Commented Aug 15, 2012 at 4:29

2 Answers 2

4

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.

answered Aug 15, 2012 at 3:00
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, sorry for completely forgetting that
2

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.

answered Aug 15, 2012 at 3:21

1 Comment

I added mainPlayer = new Player() and made it static.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.