【发布时间】:2020-04-03 04:14:57
【问题描述】:
我是编程初学者,我想用Panels 创建一个小“游戏”。
(以后也许我会换成PictureBox,但现在还可以)
代码:
private void Form1_Load(object sender, EventArgs e)
{
int size = 20;
int quantity = 10;
Random rnd = new Random();
for (int y = 0; y < quantity; y++)
{
for (int x = 0; x < quantity; x++)
{
Color randomColor = Color.FromArgb(
rnd.Next(256), rnd.Next(256), rnd.Next(256)
);
Panel panel = new Panel
{
Size = new Size(size, size),
Location = new Point(x * size, y * size),
BorderStyle = BorderStyle.FixedSingle,
BackColor = randomColor
};
Controls.Add(panel);
//panel.Click += Panel_Click;
}
}
}
我有两个问题:
- 如何设置
5到每个Panel的像素距离? - 我应该将这些面板创建放在 构造函数 中吗?我看到人们更喜欢这样。
【问题讨论】:
-
您可以将面板(或其他)添加到 TableLayoutPanel 或 FlowLayoutPanel(取决于您要查找的布局类型)。请注意,控件的
Margin属性决定了与其他控件的距离(它创建了一种不可见 外部边框)。