我想創建簡單的繪圖程序;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