Search code examples
javaswingpaintmouselistenermousemotionlistener

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException - paint()


i'm testing another simple program for drawing a line. First problem is the error.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at GUI$2.paint(GUI.java:57)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)
    at javax.swing.JComponent.paintChildren(Unknown Source)
    at javax.swing.JComponent.paint(Unknown Source)

This is the code for line 57 g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);

panel = new JPanel(){
        Point pointStart = null;
        Point pointEnd = null;
        int x = 1;
        {   
            addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent e){
                    pointStart = e.getPoint();
                }
                public void mouseReleased(MouseEvent e){
                    pointEnd = e.getPoint();
                }
            });
            addMouseMotionListener(new MouseAdapter(){
                public void mouseMoved(MouseEvent e){
                    pointEnd = e.getPoint();
                }
                public void mouseDragged(MouseEvent e){
                    pointEnd = e.getPoint();
                    repaint();
                }
            });
        }
        public void paint(Graphics g){
            super.paint(g);
            g.setColor(a);
            g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
        }
    };

If i can ask, how do i save the lines that has been drawn? Thanks


Solution

  • Try this (note that this is the paintComponent() method, not paint()):

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(a);
        if(pointStart!=null && pointEnd!=null){
            g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
        }
    }