I want do draw a rectangle in my JFrame window, but I'am always getting a nullpointer error..
Why is it happening? what is the best (correct) way to draw graphics like rectangles, gradients, etc or something like falling snow in swing?
This is the Exception:
Exception in thread "Thread-0" java.lang.NullPointerException
at gui.Window.run(Window.java:24)
at gui.Window$1.run(Window.java:34)
at java.lang.Thread.run(Unknown Source)
And source:
public class Window extends JFrame implements Runnable {
private boolean run = true;
public Window() {
super.setSize(500, 500);
super.setTitle("MY GUI");
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setContentPane(new Container());
}
@Override
public void run() {
Graphics g = super.getContentPane().getGraphics();
while (this.run) {
g.setColor(new Color(0, 0, 0, 255));
g.fillRect(0, 0, 200, 200);
}
}
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
Window window = new Window();
window.run();
}
}).start();
}
}
Error line 24:
g.setColor(new Color(0, 0, 0, 255));
Why is it doing that?