简体   繁体   中英

java swing timer not going off

I can't seem to get this timer to go off. the program compiles and from my understanding this should ping every 1000ms or 1 second and perform the lines in the actionPerformed{} function.

public void stringGeneration(String args[]){

        ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                String fullIstring = java.lang.String.valueOf(injectString[0] + injectString[1] + injectString[2] + injectString[3] + injectString[4]);
                jLabel3.setText(fullIstring);
                System.out.println("output");
            }
        };
        Timer timer = new Timer(1000, taskPerformer);
        timer.setRepeats(true);
        timer.start();

        //Thread.sleep(500);
        }

This is how i would to a scheduled task in java:

import java.util.TimerTask;

class HeartBeatTask extends TimerTask {

private int timerInterval;

public HeartBeatTask(int timeInterval)
{
    this.timerInterval = timeInterval;
}

public void run() 
{
    // Your  function call to schedule here

}
public static void main(String[] args)
    {
        java.util.Timer t1 = new java.util.Timer();

        HeartBeatTask tt = new HeartBeatTask();
        t1.schedule(tt, 0, 1000 * 60 * 2);
        }

}

Hope that helps

i just gave you an example and not something to copy paste. But you can try this if you want to try as is. In your case the above example should look like:

class HeartBeatTask extends TimerTask {

        private int timerInterval;

        public HeartBeatTask(int timeInterval)
        {
            this.timerInterval = timeInterval;
        }

        public void run() 
        {
            String fullIstring = java.lang.String.valueOf(injectString[0] + injectString[1] + injectString[2] + injectString[3] + injectString[4]);
                        jLabel3.setText(fullIstring);
                        System.out.println("output");

        }

      }

Your method will then call the above class like this:

public void stringGeneration(String args[]){
     HeartBeatTask tt = new HeartBeatTask();
                t1.schedule(tt, 0, 1000 * 60 * 2);

            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM