在自定义 JPanel 中使用 Graphics2D 出现 NullPointerException
我正在扩展 JPanel 来制作自定义绘图面板,但收到 NullPointerException 并且无法找出原因。我已经删除了代码,直到它变得非常简单,但错误仍然发生。
package testdraw;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
public DrawPanel() {
this.Draw();
}
public void Draw(){
Graphics g = this.getGraphics();
Graphics2D g2d = (Graphics2D) g;
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHints(rh);
}
}
我收到错误:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
来自调用 setRenderingHints 方法的行。任何帮助表示赞赏。
I'm extending JPanel to make a custom drawing panel, but am getting a NullPointerException and can't work out why. I've removed code until it's pretty bare, but the error is still occuring.
package testdraw;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
public DrawPanel() {
this.Draw();
}
public void Draw(){
Graphics g = this.getGraphics();
Graphics2D g2d = (Graphics2D) g;
RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
rh.put(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHints(rh);
}
}
I'm getting the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
from the line where I call the setRenderingHints
method. Any help appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
null 来自当您调用
Graphics g = this.getGraphics();
正如 Paul 所说,您不应该在构造函数中调用它,因为面板尚不存在。最好将此代码放在重写的paintComponent()
方法中The null comes from when you call
Graphics g = this.getGraphics();
As Paul said, you shouldn't call this in the constructor because the panel doesn't exist yet. It might be better to put this code in an overriddenpaintComponent()
method您在构造函数中调用“Draw”。您应该等到它完全构建并可见后再调用 getGraphics。
You're calling "Draw" in the constructor. You should wait until it's fully constructed and visibile before calling getGraphics.
通常,draw 方法不是由面板本身调用,而是由 Java2D 框架调用。因此,它不是一个没有参数的 Draw() 方法,而是 paint(Graphics g) 方法。
在这种情况下,Graphics 永远不会为空,并且始终是一个graphics2D(只要您使用Java2 VM)。
Usually, the draw method is not called by the panel itself, but rather from the Java2D framework. As a consequence, it is not a Draw() with no parameters method, but rather the paint(Graphics g) method.
In this case, the Graphics will never be null, and will always be a graphics2D (as far as you use a Java2 VM).