简体   繁体   English

在Java程序中实现计时器

[英]Implementing a timer into a java program

I'm creating a java paint program and can't figure out how to implement a timer that starts when the GUI is opened so the user can see their time spent drawing so far. 我正在创建一个Java Paint程序,无法弄清楚如何实现在打开GUI时启动的计时器,以便用户可以看到到目前为止绘制所花费的时间。 My code is pasted below. 我的代码粘贴在下面。 I'm a complete beginner and have searched all the oracle documents and can't understand them so any help is appreciated! 我是一个完整的初学者,已经搜索了所有oracle文档,但无法理解它们,因此对您有所帮助! Hopefully there's a simple way of implementing this. 希望有一种简单的方法可以实现此目的。

I added a JLabel onto my toolbar so I can try and post the "Drawing Time: "+totalTime but it stays at 0 for some reason I don't know how to make it refresh every second... 我在工具栏上添加了一个JLabel,因此我可以尝试发布“绘图时间:” + totalTime,但是由于某些原因它保持为0,我不知道如何使其每秒刷新一次...

I would try something like this: 我会尝试这样的事情:

Set up the Global Variables (Make sure you fix your imports) 设置全局变量(确保已修复导入)

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;

then initialize the timer and counter and make sure to send the info from the counter to your label 然后初始化计时器和计数器,并确保将计数器中的信息发送到您的标签

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

This is a pretty basic example of setting up a timer, so if you just apply the steps taken in the code I've given you to your own application, you'll probably be able to get it working. 这是设置计时器的一个非常基本的示例,因此,如果仅将我提供的代码中的步骤应用到您自己的应用程序中,就可以使它正常工作。 Good luck! 祝好运!

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

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