【发布时间】:2013-12-20 17:40:40
【问题描述】:
我想在我的JFrame 窗口中绘制一个矩形,但我总是收到nullpointer 错误。
为什么会这样?绘制矩形、渐变等图形或秋千落雪等图形的最佳(正确)方法是什么?
这是个例外:
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)
来源:
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();
}
}
第 24 行错误:
g.setColor(new Color(0, 0, 0, 255));
为什么要这么做?
【问题讨论】:
-
g 可能为 null 检查 super.getContentPane().getGraphics();, 在那里设置断点并调试它..
标签: java swing exception nullpointerexception