在网格布局中创建动态按钮-创建魔方UI

6

我需要使用Windows Forms应用程序创建一个二维的魔方阵。它应该长这样:

Image of 3x3 magic Square with numbers and grid shown.

然而,用户应该能够决定正方形的大小(3x3、5x5、7x7等)。我已经在控制台应用程序中编写了代码,但我不知道如何添加二维图形。
有人已经问过这个问题(如何将结果放入GUI中?),其中一个答案是使用DataGridView,但我不确定那是否是我要找的,因为我无法使其看起来像图片。
有任何想法或建议吗?

你可以使用 TableLayoutPanel 并动态地向面板添加按钮。 - Reza Aghaei
2个回答

8
您可以使用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循环"看起来没问题,所以我不知道为什么会得到那个输出。 - Jack
我的错。它正确地显示了数字,我只是需要将窗口放大以查看整个数字(而不是只看到“24”我只能看到“2”)。再次感谢! - Jack
@Jack 没问题,你可以把窗口放大或者把字体缩小 :) - Reza Aghaei
明白了。谢谢你的信息 =) - Jack

2

您可以创建一个表单并添加一个具有此属性的 TableLayoutPanel。

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

这是结果:

输入图像描述

当您创建行和列时,要正确设置百分比,请按照以下方式进行:

输入图像描述

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

输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接