创建 Java 计时器和 TimerTask? [英] Creating a Java Timer and a TimerTask?
问题描述
我是 Java 新手,我正在尝试设置一个简单的计时器,由于使用 JavaScript 和 ActionScript 的经验,我熟悉 set_interval
,
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,
我对类还不是很熟悉所以很容易混淆,我知道我需要设置一个新的Timer
,然后设置一个TimerTask
,但是即使我现在正在查看文档,我也不知道该怎么做..
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..
所以我创建了一个 Applet,这就是我的 init
方法:
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);
推荐答案
无论你想执行什么,即绘图或 smwhat,只需定义任务并在其中实现代码即可.
Whatever you want to perfom i.e. drawing or smwhat, just define task and implement the code inside it.
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);
}
//.....
}
}
这篇关于创建 Java 计时器和 TimerTask?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!