Ilias loudrassi
Ilias loudrassi

Reputation: 13

Creating class that generate labels

I have a problem creating a class that generates labels with specific weight and height, it works on the code, but doesn't show up on the form when I create the object. how I can solve this problem guys?

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

)

how I can solve this problem?

Upvotes: 1

Views: 80

Answers (1)

高鵬翔
高鵬翔

Reputation: 2057

You can do like this: Edit from your code

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

Upvotes: 3

Related Questions