Search code examples
javapaintcomponentpong

fillOval() is not taking class variables?


I'm not sure why but in my paintComponent method, the fillOval function is not letting me pass in my other classes coordinates. It comes up with :

'Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException'

all the rectangles draw fine but just not the oval. Here is the paintComponent() method.

     public void paintComponent(Graphics graphics){
    graphics.setColor(Color.BLACK);
    graphics.fillRect(0,0,600,450);

    graphics.setColor(Color.WHITE);
    graphics.fillRect(290,0,15,450);
    graphics.fillRect(leftPaddle.getXPos(),leftPaddle.getYPos(),10,85);
    graphics.fillRect(rightPaddle.getXPos(),rightPaddle.getYPos(),10,85);
    graphics.fillOval(ball.getxPos(),ball.getyPos(),ball.getWidth(),ball.getHeight());
}

And here is my Ball class (the class which bears the coordinates).

public class Ball {
int xPos = 140;
int yPos = 50;
int width = 15;
int height = 15;

public int getWidth() {
    return width;
}

public int getxPos() {
    return xPos;
}

public int getyPos() {
    return yPos;
}

public int getHeight() {
    return height;
}

}

This is probably quite an easy fix, but I am relatively new to java, so excuse any formatting mistakes, etc.

Here is where I get the object from the MainClass :

public class PaintComponents extends JPanel{
Paddle leftPaddle;
Paddle rightPaddle;
Ball ball;

public PaintComponents(Paddle leftPaddle, Paddle rightPaddle, Ball ball) {
    this.leftPaddle = leftPaddle;
    this.rightPaddle = rightPaddle;
    this.ball = ball;
}

Solution

  • As its showing NullPointerException you might not have created the object "ball" of class Ball try adding:

    Ball ball=new Ball();
    

    in public void paintComponent(Graphics graphics)

    before using "ball".