创建Java定时器和一个TimerTask? [英] Creating a Java Timer and a TimerTask?

查看:161
本文介绍了创建Java定时器和一个TimerTask?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Java和我试图设置一个简单的定时器,我是因为使用JavaScript和ActionScript, set_interval , p>

我不那么熟悉又班,所以我感到困惑容易,我知道我需要设置一个新的定时,然后设置一个的TimerTask ,但我不明白究竟是如何做到这一点,即使我在看的文件现在..

所以,我创建了一个小程序,这是我的的init 方法:

 公共无效的init(){
    TimerTask的myTask;
    定时器myTimer;
    myTimer.schedule(myTask,5000);
}

我如何实际设置任务code?
我希望它像做

  g.drawString(显示一些文字在这里变化的变量,10,10);


解决方案

至于说很多精彩的用户#1,在这里正确的想法是使用的 javax.swing.Timer中。这里有一个小$ C的帮助$ C片段。不要问任何问题,就是抓不到,我会尽量提供同样的信息。

 进口java.awt中的*。
java.awt.event中导入*。
进口了java.util.Random;
进口的javax.swing *。公共类DrawStringWithTimer
{
    私人最终诠释WIDTH = 400;
    私人最终诠释HEIGHT = 300;
    私人定时器定时器;
    私人诠释X;
    私人诠释Ÿ;
    私人诠释柜台;
    私人随机随机的;
    私有String []消息= {
                                    宾果,我在
                                    你能相信这一点!
                                    你在想还有什么呢?
                                    AHHA,好像你现在迷惑!
                                    让残疾人和征服:-)
                                };
    私人CustomPanel的contentPane;    私人的ActionListener timerAction =新的ActionListener()
    {
        @覆盖
        公共无效的actionPerformed(ActionEvent的AE)
        {
            如果(反== 5)
                计数器= 0;
            / *
             *创建随机数的地方
             * x是等于零或
             *比WIDTH和y就越小
             *等于零或小于高度。
             *我们获得的价值
             *消息数组与计数器变量
             *和传球这setValues​​方法的功能,
             *,以便它可以触发重绘()
             *要求,因为的状态
             *对象现在已经改变。
             * /
            X = random.nextInt(宽);
            Y = random.nextInt(高度);
            contentPane.setValues​​(X,Y,消息[计数器]);
            反++;
        }
    };    公共DrawStringWithTimer()
    {
        计数器= 0;
        X = Y = 10;
        随机=新的随机();
    }    私人无效displayGUI()
    {
        JFrame的帧=新的JFrame(绘画String示例);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        的contentPane =新CustomPanel(宽度,高度);        frame.setContentPane(的contentPane);
        frame.pack();
        frame.setLocationByPlatform(真);
        frame.setVisible(真);
        / *
         * javax.swing.Timer中的是你所需要的
         与定时器相关打交道时*
         *使用时,秋千任务。
         *欲了解更多信息请访问链接
         *由@trashgod规定,在
         * 注释。
         *两个参数的构造函数
         *指定为延迟和
         * ActionListener的关联
         *此计时器对象。
         * /
        定时器=新定时器(2000,timerAction);
        timer.start();
    }    公共静态无效的主要(字符串参数... args)
    {
        SwingUtilities.invokeLater(Runnable的新()
        {
            @覆盖
            公共无效的run()
            {
                新DrawStringWithTimer()displayGUI()。
            }
        });
    }
}类CustomPanel继承JPanel
{
    私人最终诠释GAP = 10;
    私人诠释宽度;
    私人诠释高度;
    私人诠释X;
    私人诠释Ÿ;
    私人字符串消息=;    公共CustomPanel(INT W,INT高)
    {
        宽度= W;
        高度= H;        setOpaque(真);
        的setBackground(Color.WHITE);
        setBorder(BorderFactory.createEmptyBorder(GAP,GAP,GAP,GAP));
    }    公共无效setValues​​方法(INT X,INT Y,弦乐味精)
    {
        this.x = X;
        this.y = Y;
        消息=味精;        / *
         *由于变量的状态会发生变化,
         *重绘()将调用的paintComponent()
         *方法间接摇摆本身。
         * /
        重绘();
    }    @覆盖
    公共尺寸的get preferredSize()
    {
        返程(新尺寸(宽,高));
    }    @覆盖
    保护无效paintComponent(图形G)
    {
        / *
         *以下行用于绘制的JPanel
         *在通常的Java方式首位。
         * /
        super.paintComponent方法(G);
        / *
         *这条线是用来绘制动态
         *字符串在给定位置。
         * /
        g.drawString(消息,X,Y);
    }
}

I'm new to Java and I'm trying to set a simple timer, I'm familiar with set_interval, because of experience with JavaScript and ActionScript,

I'm not so familiar with classes yet so I get confused easily, I understand that I need to set a new Timer, and then set a TimerTask, but I don't get how exactly to do it even though I'm looking at the documentation right now..

So I created an Applet, and that's my init method:

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

How do I actually set the task code? I wanted it to do something like

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

解决方案

As told by many a wonderful Stackoverflow users, the right idea in here is to use the javax.swing.TImer. Here is one small code snippet for your help. Do ask any question, that is beyond your grasp, I will try to provide information likewise.

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

这篇关于创建Java定时器和一个TimerTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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