Java 如何使计时器在每次调用方法时重新启动?
因此,我为我正在制作的游戏制作了一个倒计时计时器,它需要一个计时器来计算每一轮后用户的总积分。因此,我需要在每轮比赛后重置我的30秒计时器。所以我想我可以做一个方法来重置我的计时器,这样每当需要改变回合时,它就可以被一个按钮调用。但是,我觉得timer类没有内置重置功能,所以我尝试取消计时器,然后重新启动,但没有效果。有关于如何重新启动计时器的帮助吗Java 如何使计时器在每次调用方法时重新启动?,java,timer,Java,Timer,因此,我为我正在制作的游戏制作了一个倒计时计时器,它需要一个计时器来计算每一轮后用户的总积分。因此,我需要在每轮比赛后重置我的30秒计时器。所以我想我可以做一个方法来重置我的计时器,这样每当需要改变回合时,它就可以被一个按钮调用。但是,我觉得timer类没有内置重置功能,所以我尝试取消计时器,然后重新启动,但没有效果。有关于如何重新启动计时器的帮助吗 public class TimerPanel extends JPanel{ private Timer timer; pri
public class TimerPanel extends JPanel{
private Timer timer;
private Timer timer2;
private long startTime = -1;
public long duration = 30000;
public boolean paused = false;
public long remainingDuration = 0;
long clockTime;
private JLabel label;
public void stopTimer() {
this.timer.stop();
}
public void startTimer() {
if (!timer.isRunning()) {
if(paused) {
duration = remainingDuration;
paused = false;
}
else {
duration = 30000;
}
startTime = -1;
timer.start();
}
}
public void pauseTimer() {
paused = true;
this.timer.stop();
}
public int getCurrentTime() {
return (int)TimeUnit.MILLISECONDS.toSeconds(remainingDuration);
}
public int updatescore(int currentScore){
return currentScore-(int)TimeUnit.MILLISECONDS.toSeconds(remainingDuration);
}
public TimerPanel() {
setLayout(new GridBagLayout());
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
clockTime = now - startTime;
if (clockTime >= duration) {
clockTime = duration;
timer.stop();
duration = 30000;
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss");
remainingDuration = duration - clockTime;
label.setText(df.format(duration - clockTime));
}
});
timer.setInitialDelay(0);
label = new JLabel("00:30");
label.setFont(new Font("Dialog", Font.BOLD, 13));
add(label);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
}
公共类TimerPanel扩展了JPanel{
私人定时器;
私人定时器2;
私有长startTime=-1;
公共长期期限=30000;
公共布尔值=false;
公共长余留时间=0;
长时钟时间;
私人标签;
公共无效停止计时器(){
this.timer.stop();
}
公共无效startTimer(){
如果(!timer.isRunning()){
如果(暂停){
持续时间=剩余持续时间;
暂停=错误;
}
否则{
持续时间=30000;
}
开始时间=-1;
timer.start();
}
}
public void pauseTimer(){
暂停=真;
this.timer.stop();
}
public int getCurrentTime(){
返回(int)时间单位。毫秒到秒(剩余持续时间);
}
公共int updatescore(int currentScore){
返回currentScore-(int)时间单位毫秒到秒(剩余持续时间);
}
公共时间面板(){
setLayout(新的GridBagLayout());
计时器=新计时器(10,新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
如果(开始时间<0){
startTime=System.currentTimeMillis();
}
long now=System.currentTimeMillis();
时钟时间=现在-开始时间;
如果(时钟时间>=持续时间){
时钟时间=持续时间;
timer.stop();
持续时间=30000;
}
SimpleDataFormat df=新SimpleDataFormat(“mm:ss”);
剩余持续时间=持续时间-时钟时间;
label.setText(df.format(duration-clockTime));
}
});
timer.setInitialDelay(0);
标签=新的JLabel(“00:30”);
label.setFont(新字体(“Dialog”,Font.BOLD,13));
添加(标签);
}
@凌驾
公共维度getPreferredSize(){
返回新维度(50,50);
}
}