繁体   English   中英

在Java程序中实现计时器

[英]Implementing a timer into a java program

我正在创建一个Java Paint程序,无法弄清楚如何实现在打开GUI时启动的计时器,以便用户可以看到到目前为止绘制所花费的时间。 我的代码粘贴在下面。 我是一个完整的初学者,已经搜索了所有oracle文档,但无法理解它们,因此对您有所帮助! 希望有一种简单的方法可以实现此目的。

我在工具栏上添加了一个JLabel,因此我可以尝试发布“绘图时间:” + totalTime,但是由于某些原因它保持为0,我不知道如何使其每秒刷新一次...

我会尝试这样的事情:

设置全局变量(确保已修复导入)

public class MainWindow extends javax.swing.JFrame implements ActionListener{

//global variable for tracking time
Timer timer;
final int DELAY = 1000;   //the delay for the timer (1000 milliseconds)
int myCounter;

然后初始化计时器和计数器,并确保将计数器中的信息发送到您的标签

public MainWindow() {
    initComponents();

    //initialize the timer and the counter
    timer = new Timer(DELAY, this);
    timer.start();
    myCounter = 0;
}

//method needed for the timer, since this class implements ActionListener
//this method will get called however often the DELAY is set for
@Override
public void actionPerformed(ActionEvent e){
    myCounter++;
    labelOutput.setText(Integer.toString(myCounter));
}//end of method

这是设置计时器的一个非常基本的示例,因此,如果仅将我提供的代码中的步骤应用到您自己的应用程序中,就可以使它正常工作。 祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM