0

I'm trying to figure out why I am getting this error, but so far no results.

Exception in thread "Thread-2" java.lang.NullPointerException
    at Help.render(Help.java:22)
    at Game.render(Game.java:246)
    at Game.run(Game.java:123)
    at java.lang.Thread.run(Unknown Source)

I'm trying to run a method from another class which always results in this kind of error.

public void centerText ( String m , Graphics g,  int y){

        FontMetrics fm = g.getFontMetrics ( g.getFont() );
        int sw = fm.stringWidth ( m );
        g.drawString ( m , ( Game.WIDTH * Game.SCALE + sw ) / 2 - sw , y + sw /2);
    }

That's the method from the Menu class, which is a game state.

Now, I try to execute this method from another class called Help, which is another game state.

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Help {

    Menu menu;

    public void render(Graphics g) {

        Graphics2D g2d = (Graphics2D) g;

        g.setColor(Color.white);
        Rectangle test = new Rectangle(Game.WIDTH * Game.SCALE / 2 - 50, 350, 100, 50);
        g2d.draw(test);

        menu.centerText("Hello WOrld", g, 100);

    }

    public void tick() {

    }
}

Am I missing something, if so, what ? Thanks.

  • You should create an object for Menu. Menu menu = new Menu();// It is a sample if the class contain default constructor then you can create object like this – Jinu P C Nov 20 '16 at 19:29

1 Answers1

0

You haven't created an instance of menu. Currently it's null. You can't invoke anything on null.

Is Menu java's built-in class? Create an instance of it.

Menu menu = new Menu();

What is a NullPointerException and how do I fix it?

Community
  • 1
  • 1
denvercoder9
  • 2,979
  • 3
  • 28
  • 41