java编写计时器

一、注意:

1:后台循环数据要在前端显示必须在线程中执行。

2:线程的处理数据要先初始化

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

public class JiShiQi extends JFrame {
    public static boolean canshu=false;
    public static JTextField xianshi=new JTextField(8);
    public static void main(String[] args) {
new JiShiQi();
    }
    public JiShiQi(){

        setTitle("计时器");
        setLayout(null);
        setVisible(true);
        setBounds(400,500,400,200);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);



        Font font=new Font("宋体",Font.PLAIN,40);
        //显示器
        add(xianshi);
        xianshi.setFont(font);
        {
            xianshi.setBounds(20,50,170,50);
            xianshi.setEditable(false);
            xianshi.validate();

        }
        JButton queren=new JButton("开始");
        add(queren);
        queren.setFont(font);
        {
            queren.setBounds(250,55,120,40);
        }
        CaoZuo caoZuo=new CaoZuo();
        caoZuo.setJTextFiled(xianshi);
        caoZuo.setJButton(queren);
        queren.addActionListener(caoZuo);
    }
}
class DonTai implements Runnable {
    public void run() {
        int h = 0, m = 0, s = 0;


        for (h = 0; h < 12; h++) {
            for (m = 0; m < 60; m++) {
                for (s = 0; s < 60; s++) {
                    try {
                        if (JiShiQi.canshu == true) {
                            Thread.sleep(1000);
                            JiShiQi.xianshi.setText(h + ":" + m + ":" + s);
                        } else {
                            return;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}

class CaoZuo implements ActionListener {
    JTextField xianshi;
    JButton queren;

    public void setJButton(JButton queren) {
        this.queren = queren;
    }

    public void actionPerformed(ActionEvent e) {
        if (JiShiQi.canshu == true) {
            JiShiQi.canshu = false;
            queren.setText("开始");
        } else {
            JiShiQi.canshu = true;
            queren.setText("停止");
        }

        DonTai d = new DonTai();
        Thread t = new Thread(d);
        t.start();


    }

    public void setJTextFiled(JTextField xianshi) {
        this.xianshi = xianshi;
    }
}
结果:

java编写计时器_第1张图片

 如果还有其他问题可以在评论区说明,我尽力完成,我想提升自己的同时,也想交个朋友。

你可能感兴趣的:(Java项目,java,蓝桥杯,开发语言)