停止观看按钮

时间:2011-08-03 14:46:58

标签: java swing

如何操作按钮来停止和启动时钟,而按下时我想要它停止并通过更改标签来继续计数。

现在我达到了按钮开始计数并更改标签后不起作用。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Ex1 extends JFrame implements Runnable {

    int time = 0;
    JLabel lb1 = new JLabel("Hours:");
    JLabel lb2 = new JLabel("Minutes:");
    JLabel lb3 = new JLabel("Seconds:");
    JTextField hrs = new JTextField(10);
    JTextField mts = new JTextField(10);
    JTextField scd = new JTextField(10);
    JPanel Lcontent = new JPanel();
    Thread t = new Thread(this);
    boolean flag = false;
    JButton stp = new JButton("Start");
    JFrame fr1 = new JFrame("Swing Window");
    Container cp;
    int mnts = 0;
    int hors = 0;

    public Ex1() {
        fr1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fr1.setSize(700, 90);
        fr1.setResizable(true);
        cp = fr1.getContentPane();
        cp.setLayout(new FlowLayout());
        cp.add(lb1);
        cp.add(hrs);
        cp.add(lb2);
        cp.add(mts);
        cp.add(lb3);
        cp.add(scd);
        cp.add(stp);

        stp.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                if (flag == false) {
                    stp.setText("Stop");
                    t.start();
                }
                flag = true;
                //stp.setText("Start");
                //t.stop();
            }
        });
        fr1.show();
    }

    public void run() {
        while (flag) {
            try {
                Thread.sleep(1000);
                time++;
                scd.setText("" + time);
                if (time > 59) {
                    mnts++;
                    mts.setText("" + mnts);
                    time = 0;
                }
                if (mnts > 59) {
                    hors++;
                    hrs.setText("" + hors);
                    mnts = 0;
                }
            } catch (InterruptedException e) {
            }
        }
    }

    public static void main(String[] args) {
        new Ex1();
    }
}

1 个答案:

答案 0 :(得分:2)

应该在EDT上更新Swing组件的属性。由mre提供的上述链接将提供有关此内容的更多信息。确保在EDT上执行重复代码的简单方法是使用Swing Timer。

有关详细信息,请参阅How to Use Swing Timers