我想创建简单的绘图程序;Graphics2D对象总是给NullPointerException
我在这里我的程序的mousePressed和的mouseDragged事件:
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();
}
但是,当我试着画出成才,它总是给"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"
在这一行graphics2D.drawLine(touch.x, touch.y, p.x, p.y);
我也overrided方法的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);
}
而我明确的方法是:
public void clear(){
graphics2D.setPaint(Color.white);
graphics2D.fillRect(0, 0, getSize().width, getSize().height);
graphics2D.setPaint(Color.black);
repaint();
}
我该怎么办?
感谢
我也重写了paintComponent(Graphics g)方法 – CanCeylan
@CanCeylan:你不能在mouseDragged(...)方法中绘制你的行。这是行不通的。存储您从MouseEvent获得的点并在paintComponent(...)中执行线条绘制。 –
但我的出发点是这个链接:http://forum.codecall.net/java-tutorials/31180-java-mini-paint-program.html。在该链接中,我可以在mouseDragged方法中绘制线条。我想在我的GUI中应用此架构 – CanCeylan