繁体   English   中英

创建Java计时器和TimerTask?

[英]Creating a Java Timer and a TimerTask?

我是Java的新手,我想设置一个简单的计时器,由于对JavaScript和ActionScript的使用经验,我对set_interval很熟悉,

我对类还不太熟悉,所以很容易感到困惑,我知道我需要设置一个新的Timer ,然后再设置一个TimerTask ,但是即使我在看,我也没有确切地做到这一点现在的文档。

所以我创建了一个Applet,这就是我的init方法:

public void init() {
    TimerTask myTask;
    Timer myTimer;
    myTimer.schedule(myTask,5000);
}

我实际上如何设置任务代码? 我希望它做类似的事情

g.drawString("Display some text with changing variables here",10,10);

无论您要执行什么操作(即绘图或涂抹),只需定义任务并在其中执行代码即可。

import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class TimerApplet extends JApplet {

  String someText;
  int count = 0;

  public TimerApplet() {
    Timer time = new Timer();
    Сalculate calculate = new Сalculate();
    time.schedule(calculate, 1 * 1000, 1000);
  }

  class Сalculate extends TimerTask {

    @Override
    public void run() {
      count++;
      System.out.println("working.. "+count);
      someText = "Display some text with changing variables here.." +count;
      repaint();

    }
  }

  //This is how do you actually code.
  @Override
  public void paint(Graphics g)//Paint method to display our message
  {
//    super.paint(g);   flickering
    Graphics2D g2d = (Graphics2D)g;
    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, getWidth(), getHeight());
    if (someText != null) {
      g2d.setColor(Color.BLACK);
      g2d.drawString(someText,10,10);
    }

    //.....
  }
}

正如许多出色的Stackoverflow用户所说的那样,此处的正确想法是使用javax.swing.TImer 这是一个小代码段,可为您提供帮助。 请问任何您无法控制的问题,我将同样尝试提供信息。

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;

public class DrawStringWithTimer
{
    private final int WIDTH = 400;
    private final int HEIGHT = 300;
    private Timer timer;
    private int x;
    private int y;
    private int counter;
    private Random random;
    private String[] messages = {
                                    "Bingo, I am ON",
                                    "Can you believe this !!",
                                    "What else you thinking about ?",
                                    "Ahha, seems like you are confused now !!",
                                    "Lets Roll and Conquer :-)"
                                };
    private CustomPanel contentPane;

    private ActionListener timerAction = new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent ae)
        {
            if (counter == 5)
                counter = 0;
            /*
             * Creating random numbers where 
             * x will be equal to zero or 
             * less than WIDTH and y will be
             * equal to zero or less than HEIGHT.
             * And we getting the value of the
             * messages Array with counter variable
             * and passing this to setValues function,
             * so that it can trigger a repaint()
             * request, since the state of the 
             * object has changed now.
             */ 
            x = random.nextInt(WIDTH);
            y = random.nextInt(HEIGHT);
            contentPane.setValues(x, y, messages[counter]);
            counter++;
        }
    };

    public DrawStringWithTimer()
    {
        counter = 0;
        x = y = 10;
        random = new Random();
    }

    private void displayGUI()
    {
        JFrame frame = new JFrame("Drawing String Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        contentPane = new CustomPanel(WIDTH, HEIGHT);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        /*
         * javax.swing.Timer is what you need
         * when dealing with Timer related
         * task when using Swing.
         * For more info visit the link
         * as specified by @trashgod, in the
         * comments.
         * Two arguments to the constructor
         * specify as the delay and the 
         * ActionListener associated with 
         * this Timer Object.
         */
        timer = new Timer(2000, timerAction);
        timer.start();
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new DrawStringWithTimer().displayGUI();
            }
        });
    }
}

class CustomPanel extends JPanel
{
    private final int GAP = 10;
    private int width;
    private int height;
    private int x;
    private int y;
    private String message = "";

    public CustomPanel(int w, int h)
    {
        width = w;
        height = h;

        setOpaque(true);
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
    }

    public void setValues(int x, int y, String msg)
    {
        this.x = x;
        this.y = y;
        message = msg;

        /*
         * As the state of the variables will change,
         * repaint() will call the paintComponent()
         * method indirectly by Swing itself. 
         */
        repaint();
    }

    @Override
    public Dimension getPreferredSize()
    {
        return (new Dimension(width, height));
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        /*
         * Below line is used to draw the JPanel
         * in the usual Java way first.
         */
        super.paintComponent(g);
        /*
         * This line is used to draw the dynamic
         * String at the given location.
         */
        g.drawString(message, x, y);
    }
}

您在此链接中预期的示例

计时器将一直在我们的应用程序中运行,直到应用程序关闭或没有更多工作可分配或计划为止。

TimerTask-这是具有一些功能的任务,该功能将根据时间或持续时间运行。

Timer中,我们将让TimerTask运行特定的时间或在特定的时间开始运行。

请了解其工作原理,然后将其应用于applet或任何其他

1,GCTask类扩展了TimerTask类并实现了run()方法。

2,在TimerDemo程序中,实例化Timer对象和GCTask对象。

3,使用Timer对象,使用Timer类的schedule()方法对任务对象进行调度,以在5秒钟的延迟后执行,然后每5秒钟继续执行一次。

4,main()中的while循环无限实例化了SimpleObject类型的对象(其定义如下),这些对象可立即用于垃圾回收。

import java.util.TimerTask;

public class GCTask extends TimerTask
{
    public void run()
    {
        System.out.println("Running the scheduled task...");
        System.gc();
    }
}

import java.util.Timer;
public class TimerDemo
{
    public static void main(String [] args)
    {
        Timer timer = new Timer();
        GCTask task = new GCTask();
        timer.schedule(task, 5000, 5000);
        int counter = 1;
        while(true)
        {
            new SimpleObject("Object" + counter++);
            try
            {
                Thread.sleep(500);
            }
            catch(InterruptedException e) {}
        }
    }
}

public class SimpleObject
{
    private String name;
    public SimpleObject(String n)
    {
        System.out.println("Instantiating " + n);
        name = n;
    }
    public void finalize()
    {
        System.out.println("*** " + name + " is getting garbage collected ***");
    }
}

我已经在我的小型应用程序中发现了相同的问题,我知道我的解决方案不是最好的,但是很简单。 只需在自定义内部类中使用两个自更改参数即可。 这是我的代码。

final static Random random = new Random();
 ....//other codes
static class MyTimerTask extends TimerTask {

        int index_x = random.nextInt(50);
        int index_y = random.nextInt(50);

        @Override
        public void run() {
            System.out.println("Display some text with changing variables here: " + index_x + "," + index_y);
            index_x = random.nextInt(50);
            index_y = random.nextInt(50);
            System.gc();
        }

        public static MyTimerTask getInstance() {
            return new MyTimerTask();
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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