开发者

NullPointerException using Graphics2D in custom JPanel

I'm extending JPanel to make a custom drawing panel, but am getting a NullPointerException and can't work out why. I've removed 开发者_JS百科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.


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 overridden paintComponent() method


You're calling "Draw" in the constructor. You should wait until it's fully constructed and visibile before calling getGraphics.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜