2015-11-30 170 views
0

林創建其中用戶輸入nimber到文本框的GUI接口,數然後被加到作爲參數傳遞給CurrentAccount的對象。然後將該數字加上或減去一個隨機值。我希望這種情況每5秒發生一次,在公式完成後取值並加或減一個值,直到用戶告訴它停止。到目前爲止,我已經創建了這個代碼來決定是否應該添加一個隨機數字,生成隨機數字,將其添加或減去帳戶餘額,然後將帳戶餘額打印到文本字段。使用Thread.sleep代碼(5000)方法執行代碼每x秒

//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"); 
    } 
} 

香港專業教育學院嘗試,但必須把它放在錯誤的地方,因爲它停留5秒的創建按鈕,並打印出自身的平衡。任何關於這件事的幫助都會很大。另外我有一個方法來檢測用戶輸入,顯然是一個按鈕上的動作監聽器來調用它和這個方法。

[修改後的評論] 我也嘗試過使用一個計時器來循環代碼,但我似乎無法得到它指向正確的代碼重複,因爲它只是沒有做任何事情,而不是填滿內存。

ActionListener timerListener = new ActionListener() 
     { 
      public void actionPerformed(ActionEvent evt) 
      { 
       ControlPanel.this.simulate(); 
      } 
     }; 
     Timer theTimer = new Timer(5000,timerListener); 
+1

看看'java.swing.util.Timer'。它可以爲GUI線程定期安排任務。 http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer。html – markspace

+0

謝謝你,我試過一個計時器,我會修改我的評論以顯示我的代碼,我的問題是它沒有被調用,所以我顯然沒有把它指向正確的代碼 – brushbrushbrush

回答

1

在這裏你都爲java.util.Timer一個例子:

我們需要一個任務由定時器被稱爲:MyTimerTask

import java.util.Timer; 
import java.util.TimerTask; 

public class TimerTaskExample extends TimerTask { 

    @Override 
    public void run() { 

     // Implement your Code here! 
    } 
} 

接着我們來安排一個計時器來執行此任務:

Timer timer = new Timer(); 
timer.scheduleAtFixedRate(new MyTimerTask(), 0, 10 * 1000); 

第一個參數是要執行的任務。

第二個參數指出所述第一執行前的延遲。

第三個參數是在毫秒的週期。 (這裏:執行每10秒!)

請注意,如果你想要做的事情在你的GUI與這種機制,你需要使用編輯後SwingUtilities.invokeLater()


補充:

要使用javax.swing.Timer您必須致電start()才能使定時器運行。

+1

非常感謝,它完美的作品:)這是一個重量我的腦海現在:) – brushbrushbrush

2

另一種方式來運行週期性任務可以使用ScheduledExecutorService

那麼你的代碼看起來是這樣的:

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); 

Runnable yourRunnable = new Runnable() { 
    @Override 
    public void run() { 

     // Implement your Code here! 

    } 
}; 

,然後運行您的任務:

int initialDelay = 0; 
int delay = 5; 
scheduler.scheduleWithFixedDelay(yourRunnable, initialDelay, delay, TimeUnit.SECONDS); 

你的任務可能是與調用方法取消shutdown()

scheduler.shutdown();