Перезапуск метода с помощью ActionListener

1

Я создаю таймер для создания игры, но у меня с трудом возобновляется мой метод таймера. Он приостанавливает таймер примерно на секунду, а затем продолжает подсчитывать, например: если таймер находится на 4, если нажата кнопка сброса, таймер остановится на 4 секунды, а затем возобновится до 5, 6 и т.д. Во всяком случае, чтобы исправить это?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyTimer extends Panel {


    private JLabel timeDisplay;
    private JButton resetButton;
    private JButton startButton;
    private JButton stopButton;
    Timer timer;

    public MyTimer(){

        MyTimer timer;
        startButton = new JButton("Start Timer");
        stopButton = new JButton("Stop Timer");
        timeDisplay = new JLabel("...Waiting...");
        resetButton = new JButton("Reset Timer");

        this.add(resetButton);
        this.add(startButton);
        this.add(stopButton);
        this.add(timeDisplay);

        event e = new event();
        startButton.addActionListener(e);

        event1 c = new event1();
        stopButton.addActionListener(c);

        event2 d = new event2();
        resetButton.addActionListener(d);

    }

    public class event implements ActionListener{
        public void actionPerformed(ActionEvent e){
            int count = 0;
            timeDisplay.setText("Elapsed Time in Seconds: " + count);

            TimeClass tc = new TimeClass(count);
            timer = new Timer(1000, tc);
            timer.start();
        }
    }

    public class TimeClass implements ActionListener{
        int counter;

        public TimeClass(int counter){

            this.counter = counter;

        }

        public void actionPerformed(ActionEvent e){
            counter++;

            timeDisplay.setText("Elapsed Time in Seconds: " + counter);

        }
    }

    class event1 implements ActionListener{
        public void actionPerformed (ActionEvent c){
            timer.stop();
        }
    }

    class event2 implements ActionListener{
        public void actionPerformed (ActionEvent d){
            timer.restart();
        }
    }
}
Теги:
time
actionlistener

1 ответ

0

создать глобальный счетчик в классе MyTimer

static volatile int counter;

....

class event implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        // handle the condition if start button is clicked 
        // more than once continuously.
        if (timer == null) {
            TimeClass tc = new TimeClass();
            timer = new Timer(1000, tc);
        }
        timer.start();
    }
}

class TimeClass implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        counter++;
        timeDisplay.setText("Elapsed Time in Seconds: " + counter);
    }
}

class event1 implements ActionListener {
    public void actionPerformed(ActionEvent c) {
        // handle the condition if stop is clicked before starting the timer
        if (timer != null) {
           timer.stop();
        }
    }
}

class event2 implements ActionListener {
    public void actionPerformed(ActionEvent d) {
        // reset the counter
        counter = 0;
        // handle the condition if reset is clicked before starting the timer
        if (timer != null) {
            timer.restart();
        }
    }
}
  • 0
    это работало по большей части, но когда я нажимаю кнопку запуска после сброса, ничего не происходит, он остается равным 0.
  • 0
    Хорошо, позвольте мне проверить, пока вы можете это исправить.
Показать ещё 2 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню