1

我是这方面的初学者,所以请让我放松一下。我正在尝试在单击鼠标的位置在表单窗口上绘制一个点。我在调用 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);**
        }                                             
    }
  }
}
4

2 回答 2

0

目前尚不清楚您的最终目标是什么,但使用 CreateGraphics() 绘制的那些点只是暂时的。当表单重新绘制自身时,它们将被删除,例如当您最小化和恢复时,或者如果另一个窗口遮住了您的窗口。要使它们“持久化”,请使用表单e.GraphicsPaint() 事件中提供的:

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);
        }
    }

}
于 2013-10-13T19:19:33.017 回答
0

替换 Graphics g = this.CreateGraphics();为 just g = this.CreateGraphics();因为否则您定义了一个仅存在于mainForm_Load函数范围内的新变量,而不是为在更高级别范围内定义的变量赋值convexHullForm

于 2013-10-13T18:26:48.593 回答