【发布时间】:2015-11-30 16:36:04
【问题描述】:
我正在创建一个 GUI 界面,用户在其中输入一个数字到文本字段中,然后将数字作为参数添加到 CurrentAccount 的对象。然后将此数字添加或减去随机值。我希望这每 5 秒发生一次,在等式完成后取值并添加或减去一个值,直到用户告诉它停止。到目前为止,我已经创建了这个代码来决定是否应该添加或减去随机数,生成随机数,将其添加或减去帐户余额,然后将帐户余额打印到文本字段。
//method generates a random number to determine if a value should be added or subtracted from the myBalance variable within theAccount classes and completes the equation
int month = 0;
private void simulate()
{
try
{
if(month<12)
{ //Creates instance of Random to decide if the random number should be added or subtracted to the balance
Random decider = new Random();
for (int i = 0; i < 1; i++)
{
int ans = decider.nextInt(2)+1;
//if the decider value == 1, subtract or "withdraw" random number from the balance
if (ans == 1)
{
//creates instance of Random to create random number
Random bal = new Random();
int withdrawAmount = bal.nextInt((500 - 100) + 1) + 100;
//sets account balance to the balance subtract the random number
theAccount.myBalance = theAccount.myBalance - withdrawAmount;
//increments the month timer
month++;
//prints the new balance to the transaction text field
jTextArea2.setText("The new balance is " + theAccount.myBalance );
} else
{
//if decider value == 2, add or "deposit" random number to the balance
//creates instance of Random to create random number
Random bal = new Random();
int depositAmount = bal.nextInt((500 - 100) +1) + 100;
//sets account balance to the balance plus the random number
theAccount.myBalance= theAccount.myBalance + depositAmount;
//increments the month timer
month++;
//prints the new balance to the transaction text field
jTextArea2.setText("The new balance is " + theAccount.myBalance );
}
//if the account has a balance of -£200, generate an error and reset the balance to the user inputted value
if (theAccount.myBalance < -200)
{
jTextArea1.setText("Overdraft of £200 only");
theAccount.myBalance = value;
}
//if the account has a balance of 0, generate an error as the account must always have at least £1 before entering the overdraft
if(theAccount.myBalance == 0)
{
jTextArea1.setText("An account must always have £1");
}
}
}
} catch (NullPointerException i)
{
jTextArea2.setText("Create an Account");
}
}
我尝试使用 thread.sleep(5000) 方法,但一定是把它放在了错误的位置,因为它将创建按钮卡住了 5 秒钟并自行打印出余额。对此事的任何帮助都会很棒。我也有一种检测用户输入的方法,显然还有一个按钮上的动作监听器来调用它和这个方法。
[修改评论] 我还尝试使用计时器来循环代码,但我似乎无法让它指向正确的代码来重复,因为它除了填满内存之外什么都不做。
ActionListener timerListener = new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
ControlPanel.this.simulate();
}
};
Timer theTimer = new Timer(5000,timerListener);
【问题讨论】:
-
看
java.swing.util.Timer。它可以为 GUI 线程定期安排任务。 docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html -
谢谢,我尝试了一个计时器,我将修改我的评论以显示我拥有的代码,我的问题是它没有被调用,所以我显然没有将它指向正确的代码
标签: java multithreading user-interface timer