I am working on a Java project that deals with projecting a grid to the user using the paint() method along with a JFrame and Canvas.
I have a class called Runner, which includes my main method. Within Runner, I have the java paint() method. I also have a public variable of type Player within the Runner class. The problem arises when I try to call a public function of the Player instance variable. I get the following run-time error:
Can you not call other functions from inside the paint() method? The Java documentation didn't mention that that action would be bad, as far as I can tell with my limited Java understanding.
I will include some of my code below. I will do my best to only include pieces of the code that are relevant to the problem to make your job easier.
This statement is within my class Runner:
//Player
public Player player;
Here is the code from the paint method:
public void paint(Graphics g)
{
//(Code that draws grid from 2D array to screen)
// . . .
//Draw player
int playerX = 1 + (int)numRows/2;
int playerY = 1 + (int)numCols/2;
//CAUSE OF ERROR*******************
//Sets playerX and playerY
player.setPlayerX(playerX);
player.setPlayerY(playerY);
//*********************************
array[playerX][playerY] = 1;
}
Here is the code from the class Player:
public class Player {
private int playerX;
private int playerY;
private int playerHealth;
//Constructor
Player()
{
playerHealth = 100;
}
//Getters
// . . .
//Setters
public void setPlayerX(int x)
{
playerX = x;
}
public void setPlayerY(int y)
{
playerY = y;
}
}
If more code is needed to diagnose the issue please let me know and I will happily provide it. Thank you so much for your time.