簡體   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