如何在满足某些条件的同时使用 awt、swing、Thread 实现用作计时器应用程序的代码?

How do I implement the codes which works as a timer app using awt,swing,Thread while satisfying some conditions?

我必须使用 awt、swing、Thread 制作 Java 的定时器代码。

最终应用程序的概述具有以下 4 个功能。

  1. 该应用只有一个按钮。

  2. 首先按钮在按钮本身上显示“START”。

  3. 按下按钮时动态时间显示在按钮上。

  4. 在计时时按下按钮,按钮停止计时并显示“START”。

我写了如下代码

boolean isCounting = false;

int cnt = 0;

void counter() {
    while (isCounting == true) {
        btn.setText(Integer.toString(++cnt));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

public void actionPerformed(ActionEvent e) {
    if (isCounting == true) {
        isCounting = false;
    } else {
        isCounting = true;
        counter();
    }

}

当然这段代码不满足条件,因为一旦按下按钮 按钮无法再按下,计数器也不再工作。

在此代码中,一旦按钮被按下,函数“counter”就会被调用,但按钮上的值永远不会改变,直到按钮被松开。

我必须做出满足上述条件的代码。

如何实施?

如果我正确理解了你的问题,那么我快速整理的这段代码应该对你有用。

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Testing {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Testing t = new Testing();
            }
        });
    }

    private Timer timer;
    private JFrame frame;
    private JButton btn;
    private int timePassed;

    public Testing() {

        frame = new JFrame();
        timer = new Timer(1000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                timePassed++;
                updateTimeOnButton();
            }
        });
        btn = new JButton("START");

        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (timer.isRunning()) {
                    timer.stop();
                    btn.setText("START");
                } else {
                    timePassed = 0;
                    timer.start();
                    updateTimeOnButton();
                }
            }
        });
        frame.getContentPane().add(btn);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(new Dimension(300, 300));
    }

    private void updateTimeOnButton() {
        btn.setText(timePassed + " seconds");
    }
}