Reputation: 126
I have a class with a JPanel, and paintComponent(). I also have a class that implements Runnable, and which I plan to draw images onto the paintComponent once the thread is started. My Constructor takes in the JPanel, and from there I call getGraphics(). However through testing, and searching this always seems to return null.
System.err.println("Thread Started");
isRunning = true;
System.err.println(pap.getGraphics());
Graphics g = pap.getGraphics(); //pap is the name of the JPanel
while (isRunning)
{
while(xPos <= pap.getWidth() + 1)
{
xPos+=horizontalDirection;
System.err.println(xPos);
drawImage(upImgs[1], xPos, yPos, g);
pap.repaint();
pause();
//g.drawOval(xPos, 10, 10, 10);
if(xPos >= pap.getWidth())
horizontalDirection = -horizontalDirection;
if(xPos < 1)
horizontalDirection = 1;
}
//pap.repaint();
//pause(); // let this thread sleep a bit
}
System.err.println("Thread Ended");
returns Thread Started 2 null Exception in thread "Thread-1" java.lang.nullPointerException
How can I properly get the paintComponent to draw on it from this separate class?
Upvotes: 0
Views: 242
Reputation: 5545
You can't do that. Awt/Swing are not thread safe, so drawing can only be done from the gui thread.
Upvotes: 2