【问题标题】:Dynamicly created panels location distance动态创建面板位置距离
【发布时间】: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 属性决定了与其他控件的距离(它创建了一种不可见 外部边框)。

标签: c# winforms


【解决方案1】:

您必须在Location 中添加额外的5 像素padding

 ...
 int padding  =  5;
 ... 
 Location = new Point(x * (size + padding), y * (size + padding))
 ...

让我们提取一个方法:

 private void CreateGameField() {
   int size     = 20;
   int padding  =  5;
   int quantity = 10;

   Random rnd = new Random();

   for (int y = 0; y < quantity; ++y)
     for (int x = 0; x < quantity; ++x) 
       new Panel() {
         Size        = new Size(size, size),
         Location    = new Point(x * (size + padding), y * (size + padding)),
         BorderStyle = BorderStyle.FixedSingle,
         BackColor   = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256)), 
         Parent      = this, // instead of Controls.Add(panel);
       };
 }

然后

 private void Form1_Load(object sender, EventArgs e) {   
   CreateGameField();
 }

FromLoad事件处理器是创建游戏字段的好地方;如果你愿意,你可以将CreateGameField() 放在构造函数中,但把它放在之后 InitializeComponent():

 public Form1() {
   InitializeComponent();

   CreateGameField(); 
 }

【讨论】:

  • 正是我想要的! :) 谢谢
  • 你能解释一下为什么 ++y 插入 y++ 吗?我知道区别,但没有看到这里的好处。虽然我是初学者:D
  • @Lev:这是我的老C 习惯;在旧时代(当编译器是 4 MHz PC 上的一个 32 kB 小程序时)++x(递增 x,返回它)是比 x++(存储 x,递增 x 并返回)更快和更短的选项存储x)。现在 x++++x 都是一样的,这要归功于现代优化编译器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
相关资源
最近更新 更多