创建定时器,启动定时器 ballMoveTimer = new Timer(DELAY,); ballMoveTimer.start();
时间: 2024-03-09 09:51:25 浏览: 26
在Java中,可以使用`java.util.Timer`类或`javax.swing.Timer`类来创建定时器。这两个类的使用方式有些不同。
如果你是在Swing应用程序中使用定时器,通常会使用`javax.swing.Timer`类来创建定时器。以下是一个使用`javax.swing.Timer`类创建定时器的示例:
```java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class TimerExample {
private static final int DELAY = 1000; // 延迟时间,单位为毫秒
private static int count = 0; // 计数器
public static void main(String[] args) {
JFrame frame = new JFrame("Timer Example");
JLabel label = new JLabel("Count: 0");
frame.add(label);
frame.pack();
frame.setVisible(true);
Timer timer = new Timer(DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count++;
label.setText("Count: " + count);
}
});
timer.start();
}
}
```
在此示例中,我们创建了一个计数器并在窗口中显示它。我们使用`javax.swing.Timer`类创建了一个定时器,并在每次定时器触发时更新计数器的值并更新标签。最后,我们调用`start()`方法启动定时器。
如果你是在非Swing应用程序中使用定时器,可以使用`java.util.Timer`类来创建定时器。以下是一个使用`java.util.Timer`类创建定时器的示例:
```java
import java.util.Timer;
import java.util.TimerTask;
public class TimerExample {
private static final int DELAY = 1000; // 延迟时间,单位为毫秒
private static int count = 0; // 计数器
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
count++;
System.out.println("Count: " + count);
}
}, DELAY, DELAY);
}
}
```
在此示例中,我们使用`java.util.Timer`类创建了一个定时器,并在每次定时器触发时更新计数器的值并打印出它。我们使用`schedule()`方法来安排定时器任务,并传递延迟时间和重复时间作为参数。最后,我们没有调用`start()`方法,因为定时器会自动启动。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)