2013-10-13 10 views
1

나는 이것에 초심자이다 그래서 조금 느슨하게 저를 자르십시오. 마우스를 클릭 한 위치에서 양식 창에 점을 그리려는 중입니다. g.FillEllipse에서 Null 예외가 계속 발생합니다. 나는 무엇을 놓치고 잘못 했는가?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()로 그려진 점은 일시적입니다. 최소화하고 복원 할 때 또는 다른 창이 당신을 가리는 경우와 같이 양식이 다시 칠해지면 지워집니다.

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

} 
: 그들이 "지속적"는 페인트() 이벤트 양식의에 제공된 e.Graphics를 사용하도록하려면
관련 문제