关于JPanel 点击鼠标画图的问题,会出现mousePressed空指针是为什么呢

public class iPanel extends JPanel {
private static final int FRAME_HEIGHT = 800;
private static final int FRAME_WIDTH = 800;
private JFrame frame;
private JPanel drawPanel;

private JToolBar toolbar;
private JButton lineButton;
private JButton rectangleButton;
private JButton ellipseButton;
private Color drawingColor;;
private int shape;
private int[] position;
public iPanel(){

this.frame = new JFrame("Easy Painting");
this.drawPanel = new JPanel();
toolbar = new JToolBar();
drawPanel.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {
position[2]= e.getX();
position[3] = e.getY();
paint();
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {
position[0] = e.getX();
position[1] = e.getY();
}
});
setupComponents();
}
private void setupToolbar(){
lineButton = new JButton ("line");
rectangleButton = new JButton ("rectangle");
ellipseButton = new JButton ("ellipse");
colorButton = new JButton ("color");
toolbar.add(lineButton);
toolbar.add(rectangleButton);
toolbar.add(ellipseButton);
toolbar.add(colorButton);
lineButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
shape = 0;
}
});
rectangleButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
shape = 1;
}
});
ellipseButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
shape = 2;
}
});
frame.add(toolbar, BorderLayout.NORTH);
}

private void setupComponents(){
    setupToolbar();
    frame.add(drawPanel, BorderLayout.CENTER);
    frame.setSize (FRAME_WIDTH, FRAME_HEIGHT);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint () {
    int startx = position[0];
    int starty = position[1];
    int endx = position[2];
    int endy = position[3];
    Graphics g = getGraphics();
    g.setColor(drawingColor);       
    switch (shape) {
    case 0:
        g.drawLine(startx, starty, endx, endy);
        break;
    case 1:
        g.drawRect(startx, starty, Math.abs(endx-startx), Math.abs(endy-starty));
        break;
    case 2:
        g.drawOval(startx, starty, Math.abs(endx-startx), Math.abs(endy-starty));
        break;
    case 3:
        g.drawRect(startx, starty, Math.abs(endx-startx), Math.abs(endx-startx));
        break;
    case 4:
        g.drawOval(startx, starty, Math.abs(endx-startx), Math.abs(endx-startx));
        break;          
     }  
}
public static void main(String[] args){
    new iPanel();
}

}
运行会报错:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at 1.mousePressed(java:63)
mouseReleased

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问