迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Java >

在 Java 中创建 swing 计时器

作者:迹忆客 最近更新:2023/10/16 浏览次数:

本教程介绍了如何在 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

上一篇:Java 中的排序比较器

下一篇:Java 定时器

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便