创建 class 生成标签

Creating class that generate labels

我在创建 class 时遇到问题,该 class 生成具有特定重量和高度的标签,它适用于代码,但在我创建对象时没有显示在表单上。伙计们,我该如何解决这个问题?

        class cub
        {
            public int cubWeight = 150;
            public int cubHeight = 150;

            public void createNewCub()
            {
                Label cubLabel = new Label();
                cubLabel.Size = new Size(cubWeight, cubHeight);
                cubLabel.Text = "GeeksforGeeks";
                cubLabel.Location = new Point(500, 200);

                cubLabel.Font = new Font("Calibri", 18);
                cubLabel.ForeColor = Color.Green;
                cubLabel.Padding = new Padding(6);

            }

        }

        public Form1()
        {
            InitializeComponent();
            label1.Text = "Number of cubs: " + trackBar1.Value;
            label2.Text = "Number of seconds: " + trackBar2.Value;

            cub xxx = new cub();
            xxx.createNewCub();

)

我该如何解决这个问题?

您可以这样做:根据您的代码进行编辑

public Form1()
{
    InitializeComponent();
    cub xxx = new cub();
    this.Controls.Add(xxx.createNewCub()); // Add the Label
}
class cub
{
    public int cubWeight = 150;
    public int cubHeight = 150;
    public Label createNewCub() //change void to Label
    {
        Label cubLabel = new Label();
        cubLabel.Size = new Size(cubWeight, cubHeight);
        cubLabel.Text = "GeeksforGeeks";
        cubLabel.Location = new Point(500, 200);

        cubLabel.Font = new Font("Calibri", 18);
        cubLabel.ForeColor = Color.Green;
        cubLabel.Padding = new Padding(6);
        return cubLabel;  //return label
    }
}