开发者

Graphics2D object always gives NullPointerException

开发者 https://www.devze.com 2023-04-12 16:57 出处:网络
I want to create simple drawing program; Here I my program\'s mousePressed and mouseDragged events: private void mousePressed(java.awt.event.MouseEvent evt) {

I want to create simple drawing program;

Here I my program's mousePressed and mouseDragged events:

private void mousePressed(java.awt.event.MouseEvent evt) {
    touch = evt.getPoint();
    pressed = true;
}


private void mouseDragged(java.awt.event.MouseEvent evt) {
    Point p = evt.getPoint();
    if(pressed){
        graphics2D.drawLine(touch.x, touch.y, p.x, p.y);
    }
    repaint();
}

But when I try to draw someting, it always give "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" in this line graphics2D.drawLine(touch.x, touch.y, p.x, p.y);

I also overrided the method paintComponent

public void paintComponent(Graphics g){
    if(image == null){
        image = createImage(getSize().width, getSize().height);
        graphics2D = (Graphics2D)image.getGraphics();
        graphics2D.setRenderingHint(RenderingHints开发者_JAVA技巧.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        clear();
    }
    g.drawImage(image, 0, 0, null);
}

And I the clear method is:

public void clear(){
    graphics2D.setPaint(Color.white);
    graphics2D.fillRect(0, 0, getSize().width, getSize().height);
    graphics2D.setPaint(Color.black);
    repaint();
}

What should I do ?

Thanks


You need to read up on how to draw stuff in Java: Painting in AWT and Swing

If you're using Swing to do custom painting, you should override the method paintComponent(Graphics g) on the component for which you want to do custom painting for and do the painting inside that overriden method. You will always get an initialized Graphics object in that method.


You haven't specified anything about graphics2D. My guess is that it's a field which you're never initializing, so it'll always have a null value.

You should probably actually be adding a line to some list of "lines to draw" and then actually doing the drawing part in a paint handler. That's the event to handle when you want to do any painting.


Your posted code looks reasonable. You initialize the graphics2D variable when you create your image.

Custom Painting Approaches shows two ways to do this. One of the approaches is painting to a BufferedImage, which is similiar to what you are tying to do. Compare the code to see what is different.

0

精彩评论

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

关注公众号