![](/img/trans.png)
[英]How to start using javax.swing.Timer if I already have my own Timer class?
[英]javax.swing.timer subtracts as much as I click on start button
首先嗨! 這是我關於stackoverflow的第一篇文章! 這是我第二次嘗試用Java編程,也是第一次使用gui。
我實際上有2個問題。 第一個是程序,第二個是代碼的一部分。
該程序應如何工作:
按下開始鍵時,每分鍾從01:00倒數到00:00(01:00-> 00:59-> 00:58)。 當您按停止時,它將停止倒計時(duh);當您再次按開始時,它將從01:00開始,就像第一次一樣。
程序問題:
照這樣說。 這僅在我第一次按開始時有效。 當我多次按啟動鍵時,它將從時鍾中減去該次數。 按下2次(01:00-> 00:58-> 00:56)。 按下4次(01:00-> 00:56-> 00:52)。 等等...這顯然不應該發生。
理解問題:
我很難理解為什么計時器需要一個ActionListener以及為什么在使用“空”時它可以工作。 在某些情況下,使用“ this”(我也不理解)也可以使用。
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CountdownClock extends JFrame
{
private int oneSecond = 1000; //Milliseconds
private Timer timer = new Timer(oneSecond * 60, null);
private int timerCount = 59;
public static void main(String args[])
{
new CountdownClock();
}
CountdownClock()
{
this.getContentPane().setLayout(null);
this.setBounds(800, 450, 300, 125);
final JLabel countdownLabel = new JLabel("01:00");
countdownLabel.setBounds(110, 10, 125, 30);
countdownLabel.setFont(new Font("Serif", Font.PLAIN, 30));
JButton startButton = new JButton("Start");
startButton.setBounds(10, 50, 125, 30);
startButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
timer.setRepeats(true);
timer.stop();
countdownLabel.setText("01:00");
timerCount = 59;
timer.start();
timer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if (timerCount == 0)
{
timer.stop();
countdownLabel.setText("00:00");
timerCount = 59;
}
else if (timerCount <= 9)
{
countdownLabel.setText("00:0" + String.valueOf(timerCount));
timerCount = timerCount - 1;
}
else
{
countdownLabel.setText("00:" + String.valueOf(timerCount));
timerCount = timerCount - 1;
}
}
});
}
});
JButton stopButton = new JButton("Stop");
stopButton.setBounds(150, 50, 125, 30);
stopButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
timer.stop();
countdownLabel.setText("01:00");
timerCount = 59;
}
});
add(countdownLabel);
add(startButton);
add(stopButton);
setVisible(true);
}
}
發生這種情況的原因是,每當您按下按鈕時,都將ActionListener
添加到Timer
。 因此,由於Timer
允許多個偵聽器,因此當計時器計時時,每個人都會收到通知。
為了解決這些問題,您可以在每次按下啟動按鈕時實例化一個新的Timer
( timer = new Timer()
)。 或僅在JFrame
構造函數中添加一次ActionListener。 甚至刪除監聽器(但是您應該將對它的引用保存在某個地方)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.