2014-10-17 69 views
-1

所以我正在做一个基本的yahtzee程序我c#,并试图做一个实际的GUI,而不只是使用控制台。不过,我对文本框有问题。当我滚动骰子时,我希望文本框显示滚动的数字。现在它什么都没显示。我使用两个类,一个用于实际程序,另一个用于处理gui。这是Yahtzee的类:Textbox不会更新

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Yahtzee 
{ 
    class YahtzeeScorer { 
     Random rndm = new Random(); 
     Form1 gui = new Form1(); 
     String dice1, dice2, dice3, dice4, dice5; 

     public void rollDice() 
     { 
      String a = Console.ReadLine(); 
      this.dice1 = rndm.Next(1, 7).ToString(); 
      this.gui.tbDice_SetText(this.dice1); 
     } 

     static void Main(String[] args) { 
      Application.EnableVisualStyles(); 
      Application.SetCompatibleTextRenderingDefault(false); 
      YahtzeeScorer ys = new YahtzeeScorer(); 
      Application.Run(ys.gui); 
      ys.rollDice(); 
      Console.WriteLine("The result was: " + ys.dice1); 
      Console.Read(); 
     } 

    } 
} 

这是GUI Form1类:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Yahtzee 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public void tbDice_SetText(String s) 
     { 
      //this.ActiveControl = tbDice; 
      Console.WriteLine("SetText"); 
      tbDice.Text = s; 
     } 

     public void textBox1_TextChanged(object sender, EventArgs e) 
     { 

     } 



    } 
} 

tbDice是文本框组件的名称。有任何想法吗?

回答

1

检查线路:

Application.Run(ys.gui); 
ys.rollDice(); 

rollDice()不会被调用,直到退出应用程序,因为直到它运行Main()线程将阻塞Application.Run()

取而代之,请尝试拨打ys.rollDice(),如按钮事件处理程序。

UPDATE

你通过把两方面YahtzeeScorer混合您的游戏逻辑和表示逻辑。我建议你移动游戏逻辑到这样一个单独的类:

public class YahtzeeGame 
{ 
    public string rollDice() 
    { 
     return rndm.Next(1, 7).ToString(); 
    }  
} 


public partial class Form1 : Form 
{ 
    YahtzeeGame game = new YahtzeeGame(); 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    // You need to create a new Button on your form called btnRoll and 
    // add this as its click handler: 
    public void btnRoll_Clicked(object sender, EventArgs e) 
    { 
     tbDice.Text = game.rollDice(); 
    } 
} 
+0

所以我想我不能让YahtzeeScorer的实例在Form1,我可以打电话从yahtzeescorer的buttonpress行动?我可以在YS中决定form1中的按钮应该做什么?我会感激一个例子 – Lymanax 2014-10-17 23:16:54

+0

非常感谢你的配偶,解决了我的问题! – Lymanax 2014-10-18 11:01:39