/ / java getGraphics () restituisce null, come accedere a paintComponent? - java, swing, loop, grafica, paintcomponent

java getGraphics () restituisce null, come accedere a paintComponent? - java, swing, loop, grafica, paintcomponent

Ho una lezione con JPanel, epaintComponent (). Ho anche una classe che implementa Runnable e che ho intenzione di disegnare le immagini su paintComponent una volta avviato il thread. My Constructor prende JPanel e da lì chiamo getGraphics (). Tuttavia attraverso il test, e la ricerca sembra sempre restituire 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");

ritorna Discussione iniziata 2 nullo Eccezione nella discussione "Thread-1" java.lang.nullPointerException

Come posso ottenere correttamente che paintComponent attinga da questa classe separata?

risposte:

2 per risposta № 1

Non puoi farlo. Awt / Swing non sono thread-safe, quindi il disegno può essere fatto solo dal thread gui.