一别经年
回答时间:2019-12-05
向TA提问
收藏的一个小程序。
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
public class TimerApplet extends JApplet implements ActionListener{
private JLabel lblTime=new JLabel("时间");
private JButton btnStart=new JButton("开始");
private JButton btnEnd=new JButton("结束");
private long startTime=System.currentTimeMillis();
private boolean isRun=false;
private NumberFormat numberFormat=new DecimalFormat("0.000");
public TimerApplet(){
this.setLayout(new FlowLayout());
this.add(lblTime);
this.add(btnStart);
this.add(btnEnd);
btnStart.addActionListener(this);
btnEnd.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnStart){
class TimerThread implements Runnable{
public void run() {
isRun=true;
startTime=System.currentTimeMillis();
while(isRun){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
double time=(System.currentTimeMillis()-startTime);
lblTime.setText(numberFormat.format(time/1000));
}
}
}
new Thread(new TimerThread()).start();
}
if(e.getSource()==btnEnd){
isRun=false;
}
}
}
收起
阅读全文