51,411
社区成员
发帖
与我相关
我的任务
分享package csteaching;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class C2 extends JFrame implements ActionListener,Runnable{
Thread t;
String threadName;
JTextField t1;
JButton b1;
JButton b2;
boolean flag = false;
int h=0,m=0,s=0;
public C2(){
super("TIME");
setSize(600,400);
setLayout(new GridLayout(3,1));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t1=new JTextField();
b1=new JButton("Start");
b2=new JButton("Stop");
add(t1);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Start")){
flag=true;
}
else{
flag=false;
h=0;
m=0;
s=0;
}
}
public void run(){
if(Thread.currentThread().getName().equals("timer")){
while(flag){
Timer();
}
}
if(Thread.currentThread().getName().equals("show_time")){
show_time();
}
}
public void Timer(){
try{
Thread.currentThread().sleep(1000);
}catch (InterruptedException e) {}
s++;
if(s==61){m++;s=0;}
if(m==61){h++;m=0;}
}
public void show_time(){
t1.setText(h+":"+m+":"+s);
}
public static void main(String[] args) throws InterruptedException {
C2 tt = new C2();
tt.setVisible(true);
Thread t1=new Thread(tt);
Thread t2=new Thread(tt);
t1.setName("timer");
t2.setName("show_time");
t1.start();
t2.start();
}
}