【问题标题】:Adding element to another element win forms将元素添加到另一个元素winforms
【发布时间】:2026-02-22 18:40:01
【问题描述】:

我正在将一个面板添加到另一个面板,它可以工作,但没有显示在 inspanel 中的圆圈。我该如何解决这个问题。 我正在使用下面的代码。它有效但不显示圆圈

    public static int xTemp = 0;
    public static int yTemp = 0;

    private void button1_Click(object sender, EventArgs e)
    {
        Panel insPanel = new Panel();
        Random xRandom = new Random();
        xTemp= xRandom.Next(20,100);
        Random yRandom = new Random();
        yTemp = yRandom.Next(20, 100);
        insPanel.Location = new Point(xTemp, yTemp);
        insPanel.Width=40;
        insPanel.Height = 40;
        insPanel.Visible = true;
        insPanel.BorderStyle = BorderStyle.FixedSingle;

        insPanel.Paint += new PaintEventHandler(insPanel_Paint);
        panel1.Controls.Add(insPanel);

    }

    void insPanel_Paint(object sender, PaintEventArgs e)
    {
        System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
        System.Drawing.Graphics formGraphics =this.CreateGraphics();
        formGraphics.FillEllipse(myBrush, new Rectangle(xTemp,yTemp, 10, 10));
        myBrush.Dispose();
        formGraphics.Dispose();
    }

【问题讨论】:

    标签: c# .net forms winforms


    【解决方案1】:

    主要问题:您试图在错误的坐标处绘制圆。

    xTempyTempinsPanel 相对于panel1 的坐标。但是当你画圆时,你应该使用相对于你正在绘制的面板的坐标 - insPanel

    另一个问题:每次在面板上绘制内容时,无需创建和处理图形。您可以使用来自Paint 事件处理程序参数的e.Graphics

    基于以上,您的代码可能如下所示:

    void insPanel_Paint(object sender, PaintEventArgs e)
    {
        using (var myBrush = new SolidBrush(Color.Red))
        {
            e.Graphics.FillEllipse(myBrush, new Rectangle(0, 0, 10, 10));
        }
    }
    

    另请注意 - 由于绘画事件可能会非常频繁地发生,因此最好不要每次都创建和处置画笔,而是使用缓存在您的类私有字段中的画笔。

    【讨论】:

    • 感谢 korneyev,我想再问一个问题。我正在编写一个 Windows 窗体应用程序。我正在等待这个当圈出它应该改变路线的框架并且我正在做计时器来改变圈子的位置。
    • @altandogan 您的“另一个问题”很难理解,但似乎与原始问题无关。最好将其作为另一个问题(而不是评论)提出,并在该问题中提供更多解释,您尝试过的代码以及您遇到的问题。
    【解决方案2】:

    使用e.Graphics 代替this.CreateGraphics

    System.Drawing.Graphics formGraphics = e.Graphics;
    

    另一个问题是您获得的坐标范围为20 - 100 (xRandom.Next(20,100)),而您的面板尺寸仅为40, 40

    【讨论】: