Имеется код:
package main;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import utils.Arrays;
public class Context extends JPanel implements Runnable{
//screen
public static final int DEFAULT_SCREEN_WIDTH = 640;
public static final int DEFAULT_SCREEN_HEIGHT = 480;
public static final int SCREEN_SCALE = 1;
public static int SCREEN_WIDTH;
public static int SCREEN_HEIGHT;
public boolean FULL_SCREEN;
//game
public static final int FPS = 60;
public static final long TARGET_TIME = 1000/FPS;
//thread
private Thread thread;
private boolean running;
//render
private BufferedImage canvas;
private Graphics2D g;
public Context() {
super();
if(thread == null) {
thread = new Thread(this);
thread.start();
}
setPreferredSize(new Dimension(DEFAULT_SCREEN_WIDTH * SCREEN_SCALE, DEFAULT_SCREEN_HEIGHT * SCREEN_SCALE));
setFocusable(true);
requestFocus();
}
private void initRender() {
if(! FULL_SCREEN) {
SCREEN_WIDTH = DEFAULT_SCREEN_WIDTH;
SCREEN_HEIGHT = DEFAULT_SCREEN_HEIGHT;
}
canvas = new BufferedImage(SCREEN_WIDTH, SCREEN_HEIGHT, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D) canvas.getGraphics();
running = true;
}
private void drawDisplayObjects() {
for(int i=0; i < Arrays.displayObjectList.size(); i++) {
Arrays.displayObjectList.get(i).draw(g);
}
}
private void display() {
Graphics g2 = getGraphics();
g2.drawImage(canvas, 0, 0, SCREEN_WIDTH * SCREEN_SCALE, SCREEN_HEIGHT * SCREEN_SCALE, null);
g2.dispose();
}
@Override
public void run() {
long start, elapsed, wait;
initRender();
while(running) {
start = System.nanoTime();
drawDisplayObjects();
display();
System.out.println("run");
elapsed = System.nanoTime() - start;
wait = TARGET_TIME - elapsed / 1000000;
if(wait < 0) {
wait = 5;
}
try {
Thread.sleep(wait);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Однако, при его выполнении компилятор выдает ошибку:
Exception in thread "Thread-0" java.lang.NullPointerException
Далее переопределяем метод addNotify в JPanel:
public Context() {
super();
setPreferredSize(new Dimension(DEFAULT_SCREEN_WIDTH * SCREEN_SCALE, DEFAULT_SCREEN_HEIGHT * SCREEN_SCALE));
setFocusable(true);
requestFocus();
}
public void addNotify() {
super.addNotify();
if(thread == null) {
thread = new Thread(this);
thread.start();
}
}
И все работает отлично. Вопрос заключается в том, что такое addNotify и "с чем его едят". Заранее спасибо!