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
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 initializedGraphicsobject in that method.