This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                4年前关闭。
            
                    
我正在测试另一个简单的程序来画一条线。第一个问题是错误。

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)


这是第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);
        }
    };


如果我可以问,如何保存绘制的线条?谢谢

最佳答案

尝试以下操作(请注意,这是paintComponent()方法,而不是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);
    }
}

09-04 05:43