我正在尝试用java做一个秒表,看起来像这样00:00:00,一旦按下按钮就开始计时。由于某种原因,它不能工作,但我确信我遗漏了一些东西。
for (;;)
{
if (pause == false)
{
sec++;
if (sec == 60)
{
sec = 0;
mins++;
}
if (mins == 60)
{
mins = 0;
hrs++;
}
String seconds = Integer.toString(sec);
String minutes = Integer.toString(mins);
String hours = Integer.toString(hrs);
if (sec <= 9)
{
seconds = "0" + Integer.toString(sec);
}
if (mins <= 9)
{
minutes = "0" + Integer.toString(mins);
}
if (hrs <= 9)
{
hours = "0" + Integer.toString(hrs);
}
jLabel3.setText(hours + ":" + minutes + ":" + seconds);
}发布于 2012-07-20 03:11:26
我不确定问题是什么,但是把这个代码块放在for(;;)循环中肯定是致命的。
尝试这样的代码,而不是for循环:
// "1000" here means 1000 milliseconds (1sec).
new Timer( 1000, new ActionListener(){
public void actionPerformed( ActionEvent e ){
if( pause == false ){
// ... code from above with the for(;;)
}
}
}.start(); 您可以阅读documentation for the timer class以了解更多信息。
发布于 2012-07-20 03:10:01
第一件事是迭代的执行时间不到一秒,所以你会有一个“糟糕的时间”。
您可能需要使用像System.currentTimeMillis()这样的方法来精确您的程序,使用更了解如何处理time的库,或者甚至可能需要在您的程序中简单地休眠1秒(但它不会真正精确)。
发布于 2012-07-20 03:11:12
我将假设(因为您没有提供其他证据),这只是从Main-Class“按原样”执行的。你会注意到你的数字正在以极快的速度增长,一点也不像秒表。使用Thread.sleep(1000),以便在每次迭代之间传递第二个。
编辑:如果您的暂停按钮不工作,我将假设您使用的是Swing,并且按钮在事件线程上挂起,并且没有执行任何操作。一个简单的解决方法是创建pause -> static并使用swing-worker来执行您的pause按钮试图启动的方法。
https://stackoverflow.com/questions/11567586
复制相似问题