在 Java 中创建 swing 计时器
本教程介绍了如何在 Java 中创建和调用 swing 计时器。
Time
是 Swing 中的一个类,用于根据指定的时间间隔执行任务。
要创建计时器,我们首先需要创建一个动作侦听器,然后在其中定义 actionPerformed()
方法来执行任务。之后,使用所有参数调用 Timer()
构造函数并调用 start()
方法以启动任务。
setRepeats()
方法用于根据布尔参数重复调用 actionPerformed()
或仅调用一次。此方法采用布尔参数,true 或 false,如果你想重复调用 actionPerformed()
方法,则传递 true,否则传递 false。使用 timer.stop()
方法停止任务。
让我们通过一些例子来理解。
在 Java 中创建一个 swing 计时器
在这个例子中,我们使用 Timer
类创建了一个计时器,并使用带有 actionPerformed()
方法的 ActionListener
匿名类定义了一个任务。
为了启动计时器,我们使用了 start()
方法和 stop()
方法来停止计时器。setRepeats()
方法用于重复启动任务。
timer()
构造函数接受两个参数:以毫秒为单位的延迟时间和动作侦听器的实例。请参阅下面的示例。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class SimpleTesting{
public static void main(String[] args) throws InterruptedException{
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Timer is running");
}
};
Timer timer = new Timer(400 ,taskPerformer);
timer.setRepeats(true);
timer.start();
Thread.sleep(2500);
timer.stop();
}
}
输出:
Timer is running
Timer is running
Timer is running
Timer is running
Timer is running
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中执行 SQL 查询
发布时间:2024/04/24 浏览次数:1195 分类:Python
-
本教程演示了在 Python 中对 Pandas DataFrame 执行 SQL 查询。
在 Pandas 中使用 stack() 和 unstack() 函数重塑 DataFrame
发布时间:2024/04/24 浏览次数:1289 分类:Python
-
本文讨论了 Pandas 中 stack() 和 unstack() 函数的使用。