Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中的定时器模拟_Java_Swing_Timer - Fatal编程技术网

java中的定时器模拟

java中的定时器模拟,java,swing,timer,Java,Swing,Timer,我试着模拟一个计时器。因此,在点击JFrame表单中的按钮时,我希望计时器从10倒计时到0。我希望精确到10秒。我不想找到任何代码的运行时间,因为到目前为止我找到的任何代码都给出了运行时间。例如,使用System.nanoTimer() 我试着这样做: private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // TOD

我试着模拟一个计时器。因此,在点击
JFrame
表单中的按钮时,我希望计时器从10倒计时到0。我希望精确到10秒。我不想找到任何代码的运行时间,因为到目前为止我找到的任何代码都给出了运行时间。例如,使用
System.nanoTimer()

我试着这样做:

 private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:timer
    long startTime = System.nanoTime();    
    // ... the code being measured ...  
    long targetTime=startTime+10000;
    while(System.nanoTime()<targetTime)
    {
        JOptionPane.showMessageDialog(this,targetTime-System.nanoTime());
    }
    JOptionPane.showMessageDialog(this,"time's up");
}          
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt){
//TODO在此处添加处理代码:计时器
long startTime=System.nanoTime();
//…正在测量的代码。。。
long targetTime=startTime+10000;

而(System.nanoTime()10000纳秒是10毫秒,也就是1/100秒。 使用:

相反

“我正在尝试模拟计时器”…为什么?或者更确切地说,为什么不使用Swing
计时器
?为确保准确性,以每秒快得多的速度启动计时器,并检查nano time是否动作(更改时间)。另请参见模式(在
期间,
的每个循环上都会出现阻塞对话框)会把事情搞得一团糟。为了更快地得到更好的帮助,请发布一个or。
System.currentTimeMilis