【问题标题】:Create dynamic buttons in a grid layout - Create a magic square UI在网格布局中创建动态按钮 - 创建魔方 UI
【发布时间】:2015-11-28 07:49:20
【问题描述】:

我应该使用 Windows 窗体应用程序在 2D 中创建一个魔方。它应该是这样的:

但是,用户应该能够决定正方形的大小(3x3、5x5、7x7 等)。我已经在控制台应用程序中编写了代码,但我不知道如何添加 2D 图形。

有人已经问过这个问题 (How do I put my result into a GUI?),答案之一是使用 DataGridView,但我不确定这是否是我要找的,因为我无法让它看起来像图片。

有什么想法或建议吗?

【问题讨论】:

  • 您可以使用TableLayoutPanel 并动态向面板添加按钮。

标签: c# .net winforms 2d


【解决方案1】:

您可以使用TableLayoutPanel 并将按钮动态添加到面板。

如果您不需要与按钮交互,则可以添加Label

动态创建正方形:

public void CreateSquare(int size)
{
    //Remove previously created controls and free resources
    foreach (Control item in this.Controls)
    {
        this.Controls.Remove(item);
        item.Dispose();
    }

    //Create TableLayoutPanel
    var panel = new TableLayoutPanel();
    panel.RowCount = size;
    panel.ColumnCount = size;
    panel.BackColor = Color.Black;

    //Set the equal size for columns and rows
    for (int i = 0; i < size; i++)
    {
        var percent = 100f / (float)size;
        panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percent));
        panel.RowStyles.Add(new RowStyle(SizeType.Percent, percent));
    }

    //Add buttons, if you have your desired output in an array
    //you can set the text of buttons from your array
    for (var i = 0; i < size; i++)
    {
        for (var j = 0; j < size; j++)
        {
            var button = new Button();
            button.BackColor = Color.Lime;
            button.Font = new Font(button.Font.FontFamily, 20, FontStyle.Bold);
            button.FlatStyle = FlatStyle.Flat;

            //you can set the text of buttons from your array
            //For example button.Text = array[i,j].ToString();
            button.Text = string.Format("{0}", (i) * size + j + 1);
            button.Name = string.Format("Button{0}", button.Text);
            button.Dock = DockStyle.Fill;

            //If you need interaction with buttons
            button.Click += b_Click;
            panel.Controls.Add(button, j, i);
        }
    }
    panel.Dock = DockStyle.Fill;
    this.Controls.Add(panel);
}

如果您需要与按钮交互

void button_Click(object sender, EventArgs e)
{
    var button = (Button)sender;
    //Instead put your logic here
    MessageBox.Show(string.Format("You clicked {0}", button.Text));
}

例如,你可以调用

CreateSquare(3);

截图:

【讨论】:

  • 谢谢!这非常适合 3x3 正方形。但是,当尺寸不同(5x5、7x7)时,我会得到不同的结果。 “for 循环”似乎没问题,所以我不知道为什么会得到那个输出。
  • 我的错。它正确显示了数字,我只需要放大窗口才能看到整数(而不是看到“24”,我只会看到“2”)。再次感谢!
  • @Jack 不客气,是的,你可以放大窗口或缩小字体:)
  • 知道了。感谢您的信息 =)
【解决方案2】:

你可以用这个属性创建一个Form并添加一个TableLayoutPanel

tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.BackColor = Color.Gold;

这就是结果

当您创建行和列时,以这种方式正确设置百分比:

之后,您可以在每个方块中添加一个按钮或标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2012-01-11
    • 1970-01-01
    相关资源
    最近更新 更多