CanCeylan
CanCeylan

Reputation: 3010

Graphics2D object always gives NullPointerException

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

Upvotes: 0

Views: 1671

Answers (3)

camickr
camickr

Reputation: 324197

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.

Upvotes: 0

Fredrik LS
Fredrik LS

Reputation: 1480

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503290

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.

Upvotes: 1

Related Questions