繁体   English   中英

如何在满足某些条件的同时使用 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. 首先,按钮在按钮本身上显示“开始”。

  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();
    }

}

当然,这段代码不满足条件,因为一旦按下按钮,按钮就不能再被按下,并且计数器永远不会工作。

在此代码中,一旦按下按钮,就会调用 function“计数器”,但在未按下按钮之前,按钮上的值永远不会改变。

我必须使代码满足上述条件。

我该如何实施?

如果我正确理解了您的问题,那么我快速整理的这个片段应该适合您。

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");
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM