簡體   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