[英]Java swing drawing graphics nullpointer?
我想在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));
为什么这样做呢?
您发布的代码没有意义。
首先,与Swing组件的每次交互(对repaint()
调用除外)都必须在事件分发线程中完成。
其次,运行无限循环将不断地在图形上绘制相同的东西是没有意义的。
第三,这不是它的工作方式。 您无法获得与组件关联的图形并在其上绘画。 相反,您必须重写Swing组件的paintComponent(Graphics)
方法,等待swing调用此方法,然后使用提供的Graphics参数绘制所需的任何内容。 如果要更改正在绘制的内容,则需要在此元素上调用repaint()
。 不要用JFrame那样做。 创建JComponent或JPanel的子类,并将该子类的实例添加到JFrame,然后使此JFrame可见:
public class CustomComponent extends JComponent {
@Override
public void paintComponent(Graphics g) {
// paint here
}
@Override
public Dimension getPreferredSize() {
// return preferred size here
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame f = new JFrame();
f.add(new CustomComponent());
f.pack();
f.setVisible(true);
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.