我在创建一个类时会遇到问题,该类生成具有特定重量和高度的标签,它在代码上起作用,但是在创建对象时不会显示在表单上。怎样解决这个问题呢?
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
}
}