首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实施StopWatch

实施StopWatch
EN

Stack Overflow用户
提问于 2012-07-16 03:24:29
回答 2查看 720关注 0票数 0

有人能解释一下为什么我的启动/停止按钮不工作吗?这不是一个完全实现的StopWatch,但我被困在这里了。如有任何帮助,我们不胜感激!这是我第一次在论坛上发帖,如果我的帖子中有任何问题,请告诉我。这是我的代码:

代码语言:javascript
复制
public class StopWatch {

    private static boolean tiktok;

    public static void setGo(boolean go) {
        tiktok = go;
    }

    public static void main(String[] args) {
        int counter = 0;
        StopWatch stop = new StopWatch();
        ClockFrame window = new ClockFrame("StopWatch");
        JLabel lb = window.init();
        while (true) {
            lb.setText(Integer.toString(counter++));
            if (counter == 61) {
                counter = 0;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
            }
        }
    }

}

class ClockFrame extends JFrame {
    JLabel hour, minus, sec;

    public ClockFrame(String title) {
        super(title);
    }

    JLabel init() {
        JFrame frame = new JFrame("Stop Watch");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel time = new JPanel();
        hour = new JLabel("0");
        minus = new JLabel("0");
        sec = new JLabel("0");
        time.add(hour);
        time.add(minus);
        time.add(sec);

        JPanel pane = new JPanel();
        pane.setLayout(new FlowLayout());
        JButton start = new JButton("Start");
        start.addActionListener(new startstopActionListener(true));
        JButton stop = new JButton("Stop");
        stop.addActionListener(new startstopActionListener(false));
        JButton reset = new JButton("Reset");
        pane.add(start);
        pane.add(stop);
        pane.add(reset);

        Container window = frame.getContentPane();
        window.setLayout(new GridLayout(2, 1));
        window.add(pane);
        window.add(time);

        frame.setSize(500, 200);
        frame.setVisible(true);
        return sec;
    }
}

class startstopActionListener implements ActionListener {

    private boolean b;

    public startstopActionListener(boolean b) {
        this.b = b;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        StopWatch.setGo(b);
    }
}
EN

回答 2

Stack Overflow用户

发布于 2012-07-16 03:38:02

你不尊重Swing的线程策略:

只能在事件分派thread

  • Long-running中使用
  1. Swing组件,并且应该在事件分派线程中运行阻塞方法(例如,具有更新标签的无限循环的方法)(但必须在EDT中更新标签-请参阅规则1)

阅读Swing tutorial about concurrency

票数 3
EN

Stack Overflow用户

发布于 2012-07-16 04:27:17

如果你想在Swing中做秒表,你最好看看javax.swing.Timer类。它使得定期更新Swing组件(在您的例子中是JLabel)变得非常容易。使用Timer可避免Thread.sleep调用,因为事件调度线程会阻塞UI,因此不应在事件调度线程上调用该调用。

JB Nizet已经提供了到Swing concurrency tutorial的链接。我建议你也看看这个站点的'Swing info page'的Swing并发部分中提供的链接,以及一个相关问题的my answer

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11494902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档