【问题标题】:Executing code every x seconds每 x 秒执行一次代码
【发布时间】: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


【解决方案1】:

另一种运行周期性任务的方法是使用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(); 

【讨论】:

    【解决方案2】:

    这是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来执行这个Task:

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

    第一个参数是要执行的任务。

    第二个参数表示第一次执行前的延迟。

    第三个参数是以毫秒为单位的周期。 (这里:每 10 秒执行一次!)

    请注意,如果您想在 GUI 中使用此机制执行操作,您需要使用 SwingUtilities.invokeLater()


    编辑后补充:

    要使用javax.swing.Timer,您必须调用start() 以使计时器运行。

    【讨论】:

    • 非常感谢,它运行良好 :) 这让我现在放心了 :)
    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多