每 x 秒执行一次代码 [英] Executing code every x seconds

查看:41
本文介绍了每 x 秒执行一次代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 GUI 界面,用户在其中输入一个数字到文本字段中,然后将该数字作为参数添加到 CurrentAccount 的对象中.然后将该数字与随机值相加或相减.我希望这每 5 秒发生一次,在等式完成后取值并添加或减去一个值,直到用户告诉它停止.到目前为止,我已经创建了此代码来决定是否应该添加或减去随机数,生成随机数,将其添加或减去帐户余额,然后将帐户余额打印到文本字段.

Im creating a GUI interface where the user enters a nimber into a textfield, the number is then added as a parameter to an object of CurrentAccount. This number is then added or subtracted to a randomised value. I want this to happen every 5 seconds, taking the value after the equation has been completed and adding or subtracting a value until the user tells it to stop. So far i have created this code to decide if a random number should be added of subtracted, generate the random number, add or subtract it to the account balance then print the account balance to a text field.

 //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 秒钟并自行打印出余额.对此事的任何帮助都会很棒.此外,我有一个方法来检测用户输入,显然按钮上有一个动作侦听器来调用它和这个方法.

ive tried using a thread.sleep(5000) method but must have put it in the wrong place as it stuck the create button for 5 seconds and printed out the balance on its own. Any help with this matter would be great. Also i have a method to detect the user input and obviously an action listener on the button to call it and this method.

[修改后的评论]我还尝试使用计时器来循环代码,但我似乎无法将其指向正确的代码进行重复,因为它除了填满内存之外什么都不做.

[amended comment] I also tried to use a timer to loop the code but i cant seem to get it pointed at the right code to repeat as it just doesn't do anything other than fill up memory.

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

推荐答案

以下是 java.util.Timer 的示例:

我们需要一个由定时器调用的任务:MyTimerTask

We need a task to be called by the Timer: MyTimerTask

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

public class TimerTaskExample extends TimerTask {

    @Override
    public void run() {

        // Implement your Code here!
    }
}

然后我们必须安排一个计时器来执行这个任务:

Then we have to schedule a Timer to execute this Task:

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

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

The first argument is the Task to be executed.

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

The second parameter states a delay before the first execution.

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

The third parameter is the period in milliseconds. (Here: Execute every 10 Seconds!)

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

Please note that if you want to do things in your GUI with this mechanism you need to use SwingUtilities.invokeLater()

编辑后补充:

要使用 javax.swing.Timer 你必须调用 start() 来让计时器运行.

To use javax.swing.Timer you have to call start() to make the timer run.

这篇关于每 x 秒执行一次代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆