Ernesto Segovia
Ernesto Segovia

Reputation: 51

Draw multiple circles on a Form

I'm trying to create a program that creates multiple circles when you click the mouse. The problem is that they disappear (removed) every time I click on another place. I have created a class called Ellipse where my circles are saved. Then I put all in a stack called Ellipses. I have looked at different solutions, but still the old ellipses are deleted. I want to know what I'm doing wrong.

Here is my Code.

 public partial class Form1 : Form
{
    int x,y;
    Queue<MyEllipce> ellipses = new Queue<MyEllipce>();
    MyEllipce ellipse;

    public Form1()
    {
        InitializeComponent();
        this.MouseClick += new MouseEventHandler(Form1_MouseClick);

    }
    private void Form1_Load(object sender, EventArgs e)
    {
    }
    void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        x = e.X;
        y = e.Y;
        ellipse = new MyEllipce(x, y);
        ellipses.Enqueue(ellipse);
        Invalidate();
    }

    private void btnTaBort_Click(object sender, EventArgs e)
    {
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        foreach (MyEllipce item in ellipses)
        {
            Graphics g = e.Graphics;
            MyEllipce ellipse= ellipses.Peek();
            ellipse.Draw(g, x, y);
        }
    }
}


class MyEllipce
{
    int x = 0;
    int y = 0;
    int diameter = 5;

    //Constructor
    public MyEllipce(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

   public void Draw(Graphics g, int x, int y)
    {
        SolidBrush brush = new SolidBrush(Color.Red);
        g.FillEllipse(brush,x,y,diameter,diameter);
    }
}

Upvotes: 2

Views: 620

Answers (1)

Change this

ellipse.Draw(g, x, y);

To this

item.Draw(g, x, y);

And delete the "peek" line.

Upvotes: 1

Related Questions