いくつかの条件を満たす一方で、awt、swing、Threadを使用してタイマーアプリとして機能するコードを実装するにはどうすればよいですか?

user533652886:

awt、swing、Threadを使ってJavaのタイマーコードを作らなければなりません。

最終的なアプリの概要には、以下の4つの機能があります。

  1. アプリにはボタンが1つだけあります。

  2. まず、ボタンはボタン自体に「開始」を表示します。

  3. ボタンを押すと、ボタンに動的時間が表示されます。

  4. 時間のカウント中にボタンを押すと、ボタンはカウントを停止し、「スタート」を表示します。

以下のようなコードを書きました。

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

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ