我是初学者,所以请给我一点松懈。我试图在单击鼠标的位置的窗体窗口上绘制一个点。我一直在g.FillEllipse上调用Null Exception。我错过了什么或做错了什么?
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 :(得分:0)
将Graphics g = this.CreateGraphics();
替换为g = this.CreateGraphics();
,否则您将定义一个仅存在于mainForm_Load
函数范围内的新变量,而不是为更高级别定义的变量赋值-convexHullForm
答案 1 :(得分:0)
目前尚不清楚你的最终目标是什么,但用CreateGraphics()绘制的那些点只是暂时的。当表单重新绘制时,它们将被删除,例如当您最小化和恢复时,或者如果另一个窗口遮挡了您的窗口。要使它们“持久”,请使用表单的 Paint()事件中提供的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);
}
}
}