2015-11-28 20 views
5

我應該使用Windows窗體應用程序在2D中創建一個幻方。它應該是這樣的:如何使用Windows窗體創建一個幻方塊?

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

但是,用戶應該能夠決定廣場(3×3,5×5,7×7等)的大小。我已經將代碼編寫在控制檯應用程序中,但我不知道如何添加2D圖形。

有人已經問過這個問題(How do I put my result into a GUI?),其中一個答案是使用DataGridView,但我不確定這是我在找什麼,因爲我不能讓它看起來像圖片。

任何想法或建議?

+0

您可以使用'TableLayoutPanel'並向面板動態添加按鈕。 –

回答

6

您可以使用一個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); 

截圖:

enter image description here

+0

謝謝!這對於3x3的方形非常適用。但是,當尺寸不同(5x5,7x7)時,我會得到不同的結果。 「for循環」看起來沒問題,所以我不知道爲什麼我會得到那個輸出。 – Jack

+0

我的不好。它正確顯示數字,我只需要讓窗口變大就可以看到整個數字(而不是看到「24」,我只會看到「2」)。再次感謝! – Jack

+0

@Jack歡迎您,是的,您可以使窗口變大或使字體變小:) –

3

您可以創建一個表單並添加一個TableLayoutPanel與此屬性

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

,這是結果

enter image description here

當您創建行和列,以符合正確設置的百分比通過這種方式:

enter image description here

之後,您可以在每個方塊中添加一個按鈕或標籤。

enter image description here

相關問題