2013-10-13 42 views
1

我是这个初学者,所以请给我一点点松懈。我想在单击鼠标的位置在窗体窗口上绘制一个点。我一直在g.FillEllipse中调用一个空异常。我错过了什么或做错了什么?当我使用g.FillEllipse()时,我总是收到一个Null异常。

namespace ConvexHullScan 
{ 

public partial class convexHullForm : Form 
{ 
    Graphics g; 
    //Brush blue = new SolidBrush(Color.Blue); 
    Pen bluePen = new Pen(Color.Blue, 10); 
    Pen redPen = new Pen(Color.Red); 

    public convexHullForm() 
    { 
     InitializeComponent(); 
    } 

    private void mainForm_Load(object sender, EventArgs e) 
    { 
     Graphics g = this.CreateGraphics(); 
    }  

    private void convexHullForm_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 

      int x, y; 
      Brush blue = new SolidBrush(Color.Blue); 
      x = e.X; 
      y = e.Y; 
      **g.FillEllipse(blue, x, y, 20, 20);** 
     }            
    } 
    } 
} 

回答

0

只有g = this.CreateGraphics();,否则你定义一个只住里面的mainForm_Load功能范围的新的变量,而不是将值分配给在convexHullForm

0
更高级别范围内定义的变量替换 Graphics g = this.CreateGraphics();

目前尚不清楚您的最终目标是什么,但使用CreateGraphics()绘制的这些点只是暂时的。当表单重新绘制时,它们将被擦除,例如当您最小化和还原时,或者另一个窗口遮盖了您的表单。为了让他们的“老大难”,在油漆()事件发生在表单的使用提供的e.Graphics

public partial class convexHullForm : Form 
{ 

    private List<Point> Points = new List<Point>(); 

    public convexHullForm() 
    { 
     InitializeComponent(); 
     this.Paint += new PaintEventHandler(convexHullForm_Paint); 
     this.MouseDown += new MouseEventHandler(convexHullForm_MouseDown); 
    } 

    private void convexHullForm_MouseDown(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      Points.Add(new Point(e.X, e.Y)); 
      this.Refresh(); 
     }            
    } 

    void convexHullForm_Paint(object sender, PaintEventArgs e) 
    { 
     foreach (Point pt in Points) 
     { 
      e.Graphics.FillEllipse(Brushes.Blue, pt.X, pt.Y, 20, 20); 
     } 
    } 

} 
相关问题